w3resource

Scala Program: Resizable Trait with rectangle class implementation

Scala OOP Exercise-10 with Solution

Write a Scala program that creates a trait Resizable with a method resize that changes the size of an object. Implement a class Rectangle that extends the Resizable trait.

Sample Solution:

Scala Code:

trait Resizable {
  def resize(newSize: Int): Unit
}

class Rectangle(var width: Int, var height: Int) extends Resizable {
  override def resize(newSize: Int): Unit = {
    width = newSize
    height = newSize
  }

  override def toString: String = s"Rectangle (width: $width, height: $height)"
}

object ResizableApp {
  def main(args: Array[String]): Unit = {
    val rectangle = new Rectangle(7, 4)
    println(rectangle) // Rectangle (width: 7, height: 4)

    rectangle.resize(12)
    println(rectangle) // Rectangle (width: 12, height: 12)
  }
}

Sample Output:

Rectangle (width: 7, height: 4)
Rectangle (width: 12, height: 12)

Explanation:

In the above exercise,

  • The Resizable trait is defined with a method resize that takes a newSize parameter. The "Rectangle" class extends the Resizable trait and overrides the resize method. It also defines properties like width and height to represent the rectangle's dimensions.
  • The resize method in the Rectangle class changes both the width and height to the newSize value, effectively resizing the rectangle.
  • The toString method is overridden to provide a custom string representation of the Rectangle object.

Scala Code Editor :

Previous: Triangle class with equilateral check.
Next: MathConstants object with PI and E constants.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.