Scala Program: Resizable Trait with rectangle class implementation
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:
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics