w3resource

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.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Data Classes: Special classes in Kotlin that are used to hold data. They automatically generate useful functions like toString(), equals(), and hashCode().
  • Class Properties: Understanding how to define properties inside a Kotlin class.
  • Destructuring Declarations: A Kotlin feature that allows you to extract multiple values from an object into separate variables.
  • Printing to Console: Using println() to display values.

Hints (Try Before Looking at the Solution!)

Try to solve the problem using these hints:

  • Hint 1: Define a data class named Point with properties x and y.
  • Hint 2: In the main() function, create an instance of the Point class with sample values.
  • Hint 3: Use a destructuring declaration to extract the values of x and y from the object.
  • Hint 4: Print the extracted coordinates using println().

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.



Follow us on Facebook and Twitter for latest update.