Learning Kotlin: Destructuring

Submitted by Robert MacLean on Tue, 08/14/2018 - 09:00
**More Information** * This is the 19th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) Learning a new language seems is an experience you do to 1. change jobs 1. cause your boss made you do it 1. 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 own 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 and 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` I am 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 modify 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 is the *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 parenthesis and match the names of the properties of the object. So, why is this useful for other languages? Cause in JavaScript you have the same thing! The only difference is `{` and `}` rather than parenthesis and since learning it in Kotlin I've found that I use it in my main more too.