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
val (sky, tempC) = forecast()splits a returnedPair.for ((site, tents) in camps)destructures each map entry in the loop head.- Lists destructure positionally:
val (first, second) = ....
Keywords and builtins used here
IntStringforforecastfuninmainval
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.
Step 2 of 3 in Idioms, step 20 of 27 in Language basics.