Kotlin Class: Data class point with destructuring declaration
Write a Kotlin program that creates a data class 'Point' with properties for x and y coordinates. Use a destructuring declaration to extract the coordinates.
Sample Solution:
Kotlin Code:
data class Point(val x: Int, val y: Int)
fun main() {
val point = Point(12, 20)
val (x, y) = point // Destructuring declaration
println("Coordinates: x = $x, y = $y")
}
Sample Output:
Coordinates: x = 12, y = 20
Explanation:
In the above exercise -
- First we define a data class "Point" with properties for x and y coordinates. The data modifier automatically generates useful functions such as toString, equals, and hashCode for the class.
- In the "main()" function, we create an instance of Point with x coordinate as 12 and y coordinate as 20.
- The line val (x, y) = point is a destructuring declaration. It allows us to extract the values of x and y properties from the point object and assign them to the variables x and y respectively.
- Finally, we print the extracted coordinates using the println() function.
Kotlin Editor:
Previous: Logger class with companion object for logging.
Next: Enum class Color for Object color representation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics