Object decomposition

The data class also allows us to decompose an object into properties. Simply create a list of variables and assign an object to them:

val abid = Person("Abid", 40, 6.0)
val (name, age, height) = abid

This will assign each property to the distinct variable:

data class Person(var name : String, var age: Int, var height: Double)
fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
val (name, age, height) = abid
println("name=$name age=$age height=$height")
}

There is another way to access class properties by using the component function. The data class generates a component to correspond to each property. If a class contains two properties, there will be a component1 and a component2 function:

data class Person(var name : String, var age: Int, var height: Double)
fun main(args: Array<String>) {

val abid = Person("Abid", 40, 6.0)
println("name=${abid.component1()} " +
"age=${abid.component2()} " +
"height=${abid.component3()}")
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.255