typestar

Destructuring in Kotlin

Unpack pairs, list heads and map entries where they land.

fun forecast(): Pair<String, Int> = "sleet" to -2

fun main() {
    // A Pair unpacks into two names at the assignment.
    val (sky, tempC) = forecast()
    println("$sky at $tempC C")

    val camps = mapOf("Aspen Gate" to 3, "Windy Col" to 11)
    // Map entries destructure straight in the loop head.
    for ((site, tents) in camps) {
        println("$site has $tents tents")
    }
    val (first, second) = listOf("lead", "sweep")
    println("$first then $second")
}

How it works

  1. val (sky, tempC) = forecast() splits a returned Pair.
  2. for ((site, tents) in camps) destructures each map entry in the loop head.
  3. Lists destructure positionally: val (first, second) = ....

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
430
Tokens
115
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 2 of 3 in Idioms, step 20 of 27 in Language basics.

← Previous Next →

Destructuring in other languages