Learning Kotlin: Destructuring
Note This is the 19th post in a multi-part series. If you want to read more, see our series index.
Learning a new language seems to be an experience you have to:
- change jobs,
- cause your boss made you do it, or
- cause you are a nerd. The thing I forget each time I learn a new language is that the act of learning a new language helps me be a better software developer in my primary language (the secret fourth option). Going through Kotlin has been a similar experience, and nothing jumped out more than object destructuring.
The simple use for object destructuring is to be able, in a single line, to assign multiple variables from an object. Let’s look at this example:
data class Person(val firstName: String, val surname: String, val age: Int)
fun name(person: Person) {
println("Hi ${person.firstName}")
}
fun name2(person: Person) {
println("Hi ${person.firstName} ${person.surname}")
}
fun main(args: Array<String>) {
val frank = Person("Frank", "Miller", 61)
val alan = Person("Alan", "Moore", 64)
name(frank)
name2(frank)
name(alan)
name2(alan)
}
In each of the name and name2 functions, I’m working with the Person object—but all I want are the names. I never care about the age of the people.
We could add a function now, which pulls out just the strings we want and modifies everything else to work with just the data it needs:
data class Person(val firstName: String, val surname: String, val age: Int)
fun name(firstName: String) {
println("Hi $firstName")
}
fun name2(firstName: String, surname: String) {
println("Hi $firstName $surname")
}
fun print(person: Person) {
val (firstName, surname) = person
name(firstName)
name2(firstName, surname)
}
fun main(args: Array<String>) {
val frank = Person("Frank", "Miller", 61)
val alan = Person("Alan", "Moore", 64)
print(frank)
print(alan)
}
Line 12 is the magic—that’s object destructuring. Rather than having two lines where we assign a variable to firstName and surname, we can assign them both in one line, so long as they are wrapped in parentheses and match the names of the object’s properties.
So, why is this useful for other languages? Cause in JavaScript, you have the same thing! The only difference is {} instead of parentheses—and since learning it in Kotlin, I’ve found that I use it in my main code too.