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 a new language seems is an experience you do to

  1. change jobs
  2. cause your boss made you do it
  3. 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:

  1. data class Person(val firstName: String, val surname: String, val age: Int)
  2.  
  3. fun name(person: Person) {
  4.     println("Hi ${person.firstName}")
  5. }
  6.  
  7. fun name2(person: Person) {
  8.     println("Hi ${person.firstName} ${person.surname}")
  9. }
  10.  
  11. fun main(args:Array<String>) {
  12.     val frank = Person("Frank", "Miller", 61)
  13.     val alan = Person("Alan", "Moore", 64)
  14.  
  15.     name(frank)
  16.     name2(frank)
  17.     name(alan)
  18.     name2(alan)
  19. }

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,

  1. data class Person(val firstName: String, val surname: String, val age: Int)
  2.  
  3. fun name(firstName: String) {
  4.     println("Hi $firstName")
  5. }
  6.  
  7. fun name2(firstName: String, surname: String) {
  8.     println("Hi $firstName $surname")
  9. }
  10.  
  11. fun print(person: Person) {
  12.     val (firstName, surname) = person
  13.     name(firstName)
  14.     name2(firstName, surname)
  15. }
  16.  
  17. fun main(args:Array<String>) {
  18.     val frank = Person("Frank", "Miller", 61)
  19.     val alan = Person("Alan", "Moore", 64)
  20.  
  21.     print(frank)
  22.     print(alan)
  23. }

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.