Destructuring Declarations

A Kotlin expression might well return more than one value. This does not mean “more than one value, but all stored in a single object”, though obviously Kotlin can do that too. Instead, this means literally getting more than one result from the expression:

val (something, orAnother) = gimmeStuff()

Here, gimmeStuff() will populate both something and orAnother… even though gimmeStuff() has only one return value.

This trick is called a “destructuring declaration”.

The Components of a Class

For this to work, the object returned by the expression (e.g., the object returned by gimmeStuff()) needs to implement functions named component1(), component2(), and so on. The parenthetical list of properties will use those functions in numerical order. So, the above code snippet is equivalent to:

val temp = gimmeStuff()
val something = temp.component1()
val orAnother = temp.component2()

(of course, this second snippet also sets up a temp variable that the first snippet avoids)

Many built-in classes, like Pair, implement these functions, one for every distinct piece of data. So, in the case of Pair, it implements component1() and component2(), but not others, as a Pair only holds two items.

Also, data classes implement these functions, with the numbered functions corresponding with the constructor parameter positions:

data class Person(
  val name: String,
  val quest: String,
  val airSpeedVelocityUnladenSwallow: Float
)

fun main() {
  val (who, what, waitWut) = Person("Arthur", "To seek the Holy Grail", 0.01f)
  println(who)
  println(what)
  println(waitWut)
}

Here, our Person class winds up with three component functions:

Component Function Returned Property
component1() name
component2() quest
component3() airSpeedVelocityUnladenSwallow

(note: the unit of measurement for airSpeedVelocityUnladenSwallow is in furlongs per microfortnight)


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.