Destructuring Workbook
Practice problems for Destructuring: Unpacking an Object in One Line. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
the basics
1. Unpack a data class
Given data class User(val id: Int, val name: String) and val u = User(1, "Ada"), pull id and name into two variables in one line.
Show answer Hide answer
val (id, name) = u 2. What it expands to
The declaration val (id, name) = u is shorthand for what two calls?
Show answer Hide answer
val id = u.component1()
val name = u.component2() 3. Return two values
Write minMax(nums: List<Int>) returning a data class MinMax(val min: Int, val max: Int), then destructure the result at the call site.
Show answer Hide answer
data class MinMax(val min: Int, val max: Int)
fun minMax(nums: List<Int>) = MinMax(nums.min(), nums.max())
val (low, high) = minMax(scores) loops and lambdas
4. Destructure map entries
Given a map ages, iterate it printing "<name> is <age>", destructuring each entry.
Show answer Hide answer
for ((name, age) in ages) {
println("$name is $age")
} 5. Index and value
Iterate names with both the index and the value, destructured in the loop header.
Show answer Hide answer
for ((i, name) in names.withIndex()) {
println("$i: $name")
} 6. Destructure a lambda parameter
Given val users = listOf(User(1, "Ada")), map each user to "<id>: <name>", destructuring the lambda parameter.
Show answer Hide answer
users.map { (id, name) -> "$id: $name" } skipping and custom components
7. Skip a component
Given val u = User(1, "Ada"), bind only the name, ignoring the id.
Show answer Hide answer
val (_, name) = u_ skips the component without binding a variable.
8. A List destructures too
Given val parts = "host=localhost".split("="), bind the two halves to key and value.
Show answer Hide answer
val (key, value) = "host=localhost".split("=")List provides component1 through component5, so it destructures positionally.
9. Custom components
Add component1/component2 to class Pairish(val a: Int, val b: Int) so it can be destructured.
Show answer Hide answer
class Pairish(val a: Int, val b: Int) {
operator fun component1() = a
operator fun component2() = b
}
val (x, y) = Pairish(1, 2) 10. Destructure a Triple
Bind the three values of Triple(1, 2, 3) to a, b, and c in one line.
Show answer Hide answer
val (a, b, c) = Triple(1, 2, 3)Destructuring is positional — a gets component1(), b gets component2(), and so on.
Back to the lesson, Destructuring, or on to the next one: visibility and packages.