Destructuring declarations in Kotlin

Level 5201 keystrokes

A destructuring declaration such as val (x, y) = point unpacks an object into several variables using its component1(), component2()… functions. Data classes generate them automatically, and map entries support them too, so a for loop can read key and value directly.

Kotlin code

// A data class gets component1() and component2() for x and y
1data class Point(val x: Int, val y: Int)
2
// Create a point
3val point = Point(10, 20)
// Unpack in property order: x = 10, y = 20
4val (x, y) = point
// Print x=10, y=20
5println("x=$x, y=$y")
6
// A map with two entries; mapOf keeps insertion order
7val map = mapOf("a" to 1, "b" to 2)
// Destructure each Map.Entry into key and value
8for ((key, value) in map) {
// Prints a -> 1, then b -> 2
9 println("$key -> $value")
10}

Output

x=10, y=20
a -> 1
b -> 2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • "× 8
  • (× 8
  • )× 8
  • ,× 6
  • =× 5
  • $× 4
  • :× 2
  • -× 1
  • {× 1
  • }× 1

More Kotlin examples at level 5

← Kotlin typing practice