Scala Program: Destructuring declarations in point class
Write a Scala program that creates a class Point with properties x and y coordinates. Use a destructuring declaration to extract the coordinates.
Sample Solution:
Scala Code:
Sample Output:
x-coordinate: 2 y-coordinate: 1
Explanation:
In the above exercise -
- The "Point" class is defined with properties for x and y coordinates. It is a case class, which automatically implements equality, hashing, and toString.
- The "PointApp" object contains the main method to test functionality. It creates an instance of the Point class with coordinates (5, 10).
- The line val Point(x, y) = point uses a destructuring declaration to extract the x and y values from the point object. This syntax allows you to assign x and y values directly from the point object properties.
- Finally, the program prints the extracted x and y coordinates using string interpolation.
Scala Code Editor :
Previous: MathConstants object with PI and E constants.
Next: Enum class for object color representation.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics