w3resource

Scala Program: Destructuring declarations in point class

Scala OOP Exercise-12 with Solution

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:

object PointApp {
  def main(args: Array[String]): Unit = {
    val point = Point(2, 1)
    
    val Point(x, y) = point
    
    println(s"x-coordinate: $x")  
    println(s"y-coordinate: $y") 
  }
}

case class Point(x: Int, y: Int)

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?



Follow us on Facebook and Twitter for latest update.