Destructuring Declarations
Unpack into variables.
Unpacking Objects
Sometimes you want to pull several properties out of an object at once.
Kotlin's destructuring declarations let you assign multiple variables from one object in a single line.
Basic Destructuring
Put names in parentheses on the left of =. Kotlin assigns the object's components to them in order.
Data classes support this automatically.
data class User(val name: String, val age: Int)
fun main() {
val user = User("Alice", 30)
val (name, age) = user
println(name)
println(age)
}All lessons in this course
- Declaring Data Classes
- copy and equals
- Destructuring Declarations
- Data Classes in Collections