Introduction
Destructuring helps you easily get parts of each item when you look through a list or map. It makes your code simple and clear.
for ((key, value) in map) { // use key and value } for ((first, second) in listOfPairs) { // use first and second }
val map = mapOf("a" to 1, "b" to 2) for ((key, value) in map) { println("Key: $key, Value: $value") }
val list = listOf(Pair("x", 10), Pair("y", 20)) for ((first, second) in list) { println("First: $first, Second: $second") }
fun main() { val map = mapOf("apple" to 3, "banana" to 5) for ((fruit, count) in map) { println("We have $count $fruit(s)") } }
for ((key, value) in map) { ... }for ((key, value) in map) extracts both key and value from each map entry.key and value directly inside the loop without extra calls.val map = mapOf("a" to 1, "b" to 2)for ((key, value) in map).val map = mapOf("x" to 10, "y" to 20)
for ((k, v) in map) {
println("$k$v")
}k and v.println("$k$v") prints key and value together without space, so outputs are "x10" and "y20" on separate lines.val map = mapOf("a" to 1, "b" to 2)
for (key, value in map) {
println(key + value)
}for (key, value in map) which lacks parentheses around key, value.for ((key, value) in map). Without them, it's a syntax error.val rows = listOf(Pair("id", 1), Pair("name", "Alice"), Pair("age", 30))(key, value) works to access each part.Pass the test and this pattern moves unknown