Destructuring in lambda expressions
In Chapter 4, Classes and Objects, we saw how objects can be destructured into multiple properties using destructuring declarations:
data class User(val name: String, val surname: String, val phone: String) val (name, surname, phone) = user
Since version 1.1, Kotlin can use destructuring declarations syntax for lambda parameters. To use them, you should use parentheses that include all the parameters that we want to destructure into:
val showUser: (User) -> Unit = { (name, surname, phone) -> println("$name $surname have phone number: $phone") } val user = User("Marcin", "Moskala", "+48 123 456 789") showUser(user) // Marcin Moskala have phone number: +48 123 456 789
Note
Kotlin's destructing declaration is position-based, as opposed to the property name-based destructuring declaration that can be found, for example, in TypeScript. In position-based destructuring declarations, the order of properties decides which...