Challenge - 5 Problems
Destructuring Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of destructuring a list of pairs
What is the output of this Kotlin code that uses destructuring in a for loop to iterate over a list of pairs?
Kotlin
val pairs = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3)) for ((letter, number) in pairs) { println("$letter$number") }
Attempts:
2 left
💡 Hint
Look at how the pair is split into two variables inside the loop.
✗ Incorrect
The for loop destructures each Pair into two variables: letter and number. Then it prints them concatenated, so the output is a1, b2, c3 each on a new line.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in destructuring declaration
Which option contains a syntax error when destructuring a map entry in a for loop?
Kotlin
val map = mapOf("x" to 10, "y" to 20) for ((key, value) in map) { println("$key -> $value") }
Attempts:
2 left
💡 Hint
Check the parentheses around the destructured variables.
✗ Incorrect
Option C misses parentheses around key and value, which is required for destructuring declarations in Kotlin for loops.
❓ optimization
advanced2:00remaining
Optimizing iteration with destructuring on large map
Given a large map, which option is the most efficient way to iterate with destructuring to print keys and values?
Kotlin
val largeMap = (1..1000000).associateWith { it * 2 }
Attempts:
2 left
💡 Hint
Consider the overhead of accessing values inside the loop.
✗ Incorrect
Using forEach with destructuring (option B) is efficient and concise. Option B accesses the map value by key each iteration, which is slower. Options B and C are valid but forEach with destructuring is preferred for readability and performance.
🔧 Debug
advanced2:00remaining
Debug the error in destructuring a list of triples
What error occurs when running this code and why?
Kotlin
val triples = listOf(Triple(1, 2, 3), Triple(4, 5, 6)) for ((a, b) in triples) { println("$a and $b") }
Attempts:
2 left
💡 Hint
Check how many variables Triple expects in destructuring.
✗ Incorrect
Triple requires three variables in destructuring. Using only two variables causes a type mismatch error at compile time.
🧠 Conceptual
expert2:00remaining
Understanding destructuring declarations with data classes
Given this data class and list, what is the output of the code below?
Kotlin
data class Person(val name: String, val age: Int) val people = listOf(Person("Alice", 30), Person("Bob", 25)) for ((name, age) in people) { println("$name is $age years old") }
Attempts:
2 left
💡 Hint
Data classes automatically support destructuring declarations.
✗ Incorrect
Data classes in Kotlin automatically generate componentN functions, enabling destructuring. The loop extracts name and age from each Person and prints them.