w3resource

Kotlin Class: Data class point with destructuring declaration

Kotlin Class: Exercise-17 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-17.php