Destructuring
suggest changeA destructuring declaration unpacks one object into several variables in a single statement:
val (name, age) = person
It's the Kotlin equivalent of tuple unpacking in Python or destructuring assignment in JavaScript, but it's simpler than both: it works by position, it's resolved at compile time, and it's built on one convention, the componentN() operator functions.
You can destructure:
- data classes,
PairandTriple Map.Entry, sofor ((key, value) in map)works- lists and arrays (the first five elements)
IndexedValuefromwithIndex()and regex matches viaMatchResult.destructured- any class, including ones you don't own, once you give it
componentN()functions
Structs, tuples, and records introduces destructuring alongside data classes. This article covers it in depth.
How it works
A destructuring declaration is shorthand for calling component1(), component2(), ... on the right-hand side:
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 4)
val (x, y) = p
println("x=$x y=$y")
// the same thing, written out by hand
val x2 = p.component1()
val y2 = p.component2()
println("x2=$x2 y2=$y2")
// destructured variables are ordinary local variables
var (a, b) = Point(1, 2)
a += 10
println("a=$a b=$b")
}
x=3 y=4
x2=3 y2=4
a=11 b=2
A data class gets one componentN() per property declared in its primary constructor, in declaration order. The variable names on the left don't matter to the compiler: val (y, x) = p would put 3 into y. Use val for read-only variables or var if you want to reassign them later.
Properties declared in the class body are not part of destructuring:
data class Product(val sku: String, val price: Double) {
// declared in the body: not part of componentN()
val priceWithTax = price * 1.2
}
// lists have component1()..component5(); add more if you need them
operator fun <T> List<T>.component6(): T = this[5]
fun main() {
val (sku, price) = Product("A-17", 10.0)
println("$sku $price")
val (a, b, c, d, e, f) = "1 2 3 4 5 6".split(" ")
println(a + b + c + d + e + f)
}
A-17 10.0
123456
Asking for more components than a type has is a compile error, for example val (sku, price, withTax) = Product("A-17", 10.0):
e4.kt:5:33: error: destructuring of type 'Product' requires operator function 'component3()'.
The second part of the example shows that the convention is open: List only has component1() to component5() in the standard library, but an extension component6() makes six-element destructuring compile.
Returning multiple values from a function
Kotlin functions return one value, but that value can be a Pair, a Triple or a small data class, and the caller destructures it. This is the most common use of destructuring:
data class ParseResult(val value: Int?, val error: String?)
fun parsePort(s: String): ParseResult {
val n = s.toIntOrNull() ?: return ParseResult(null, "not a number: $s")
if (n !in 1..65535) return ParseResult(null, "out of range: $n")
return ParseResult(n, null)
}
fun minMax(nums: List<Int>): Pair<Int, Int> = nums.min() to nums.max()
fun stats(nums: List<Double>): Triple<Double, Double, Double> {
val mean = nums.average()
val variance = nums.sumOf { (it - mean) * (it - mean) } / nums.size
return Triple(mean, variance, Math.sqrt(variance))
}
fun main() {
for (input in listOf("8443", "http", "70000")) {
val (port, err) = parsePort(input)
if (err != null) println("error: $err") else println("port: $port")
}
val (lo, hi) = minMax(listOf(5, 3, 9, 1))
println("lo=$lo hi=$hi")
val (mean, variance, stddev) = stats(listOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0))
println("mean=$mean variance=$variance stddev=$stddev")
// standard library functions that return pairs
val (even, odd) = (1..10).partition { it % 2 == 0 }
println("even=$even odd=$odd")
val (names, ages) = listOf("ann" to 31, "bob" to 25).unzip()
println("names=$names ages=$ages")
val (base, ext) = "report.final.pdf".let { it.substringBeforeLast('.') to it.substringAfterLast('.') }
println("base=$base ext=$ext")
}
port: 8443
error: not a number: http
error: out of range: 70000
lo=1 hi=9
mean=5.0 variance=4.0 stddev=2.0
even=[2, 4, 6, 8, 10] odd=[1, 3, 5, 7, 9]
names=[ann, bob] ages=[31, 25]
base=report.final ext=pdf
Pair and Triple are fine for private helpers and obvious pairs like min/max. For results that are part of a public API, a named data class like ParseResult documents itself: callers can still destructure it, but they can also write result.error, which is clearer than result.second.
Lists, arrays and split strings
List and all array types have component1() to component5(), so you can unpack the first few elements:
fun main() {
val (first, second, third) = listOf("a", "b", "c", "d")
println("$first $second $third")
val (r, g, b) = intArrayOf(255, 128, 0)
println("r=$r g=$g b=$b")
// parsing "key=value" lines
val line = "timeout = 30"
val (key, value) = line.split("=", limit = 2).map { it.trim() }
println("key='$key' value='$value'")
// parsing a date
val (year, month, day) = "2026-10-17".split("-").map(String::toInt)
println("year=$year month=$month day=$day")
// the list must be long enough
try {
val (k, v) = "no-equals-sign".split("=")
println("$k $v")
} catch (e: IndexOutOfBoundsException) {
println("${e::class.simpleName}: ${e.message}")
}
// check the size first, or use getOrNull
val parts = "debug".split("=")
val name = parts[0]
val flag = parts.getOrNull(1) ?: "true"
println("name=$name flag=$flag")
}
a b c
r=255 g=128 b=0
key='timeout' value='30'
year=2026 month=10 day=17
IndexOutOfBoundsException: Index: 1, Size: 1
name=debug flag=true
Extra elements are ignored, but missing ones are not: the compiler can't know the size of a list, so component2() on a one-element list throws IndexOutOfBoundsException at runtime. Destructuring the result of split() is convenient when the input format is guaranteed. For user input, check parts.size or use getOrNull().
The limit = 2 argument matters for key=value parsing: without it, a value that itself contains = would be split into more pieces, and the second component would only hold part of the value.
In for loops
A for loop can destructure each element. The most common case is iterating a map, whose entries have component1() (the key) and component2() (the value):
fun main() {
val stock = mapOf("apple" to 12, "pear" to 0, "plum" to 7)
for ((fruit, count) in stock) {
println("$fruit: $count")
}
// withIndex() gives IndexedValue(index, value)
val colors = listOf("red", "green", "blue")
for ((i, color) in colors.withIndex()) {
println("$i -> $color")
}
// zip produces pairs
val prices = listOf(1.5, 0.75, 2.0)
for ((color, price) in colors.zip(prices)) {
println("$color costs $price")
}
// a list of pairs or data classes
val moves = listOf(1 to 0, 0 to -1, -1 to 0)
var x = 0
var y = 0
for ((dx, dy) in moves) {
x += dx
y += dy
}
println("final position: ($x, $y)")
}
apple: 12
pear: 0
plum: 7
0 -> red
1 -> green
2 -> blue
red costs 1.5
green costs 0.75
blue costs 2.0
final position: (0, -1)
See Iterating over a Map in Kotlin and Looping over iterables for more about loops.
In lambda parameters
A lambda parameter can be destructured by wrapping it in parentheses. This is where destructuring is used most in idiomatic collection code:
data class Employee(val name: String, val dept: String, val salary: Int)
fun main() {
val stock = mapOf("apple" to 12, "pear" to 0, "plum" to 7)
// one parameter, destructured into two variables
stock.forEach { (fruit, count) -> println("$fruit=$count") }
// two parameters: Map.forEach from Java, takes (K, V)
stock.forEach { fruit, count -> println("$fruit:$count") }
val inStock = stock.filter { (_, count) -> count > 0 }.keys
println(inStock)
val staff = listOf(
Employee("ann", "eng", 120),
Employee("bob", "eng", 100),
Employee("cid", "ops", 90),
)
// mix a normal parameter with a destructured one
staff.forEachIndexed { i, (name, dept) -> println("${i + 1}. $name ($dept)") }
// groupBy + map: destructure the map entry, then use the list
val payroll = staff.groupBy { it.dept }
.map { (dept, people) -> dept to people.sumOf { it.salary } }
println(payroll)
// explicit types on destructured components
val top = staff.maxBy { it.salary }.let { (name: String, _, salary: Int) -> "$name earns $salary" }
println(top)
}
apple=12
pear=0
plum=7
apple:12
pear:0
plum:7
[apple, plum]
1. ann (eng)
2. bob (eng)
3. cid (ops)
[(eng, 220), (ops, 90)]
ann earns 120
The parentheses are significant:
| Lambda | Meaning |
|---|---|
{ a -> ... } |
one parameter |
{ a, b -> ... } |
two parameters |
{ (a, b) -> ... } |
one parameter, destructured into two variables |
{ a, (b, c) -> ... } |
two parameters, the second destructured |
Map.forEach { k, v -> } happens to work because the JVM's Map has a forEach that takes a two-argument function. Most functions, like map or filter on a list of pairs, take a single-argument function, and forgetting the parentheses gives a confusing error:
val pairs = listOf("a" to 1, "b" to 2)
pairs.map { name, n -> "$name$n" }
e1.kt:3:15: error: argument type mismatch: actual type is '(Pair<String, Int>, ??? (Unknown type for value parameter n)) -> String', but '(Pair<String, Int>) -> String' was expected.
e1.kt:3:23: error: cannot infer type for value parameter 'n'. Specify it explicitly.
The fix is pairs.map { (name, n) -> "$name$n" }.
Skipping components with _
Use _ for components you don't need. The compiler doesn't call componentN() for an underscore, and you can simply leave out trailing components:
class Noisy {
operator fun component1(): String { println("component1 called"); return "one" }
operator fun component2(): String { println("component2 called"); return "two" }
operator fun component3(): String { println("component3 called"); return "three" }
}
fun main() {
val (_, second) = Noisy()
println("second=$second")
println("---")
// trailing components can simply be left out
val (first) = Noisy()
println("first=$first")
}
component2 called
second=two
---
component1 called
first=one
_ also avoids "unused variable" warnings, and it can be used for unused lambda parameters in general: { _, value -> value }.
Adding destructuring to your own classes
Any class can be destructured once it has operator fun component1(), component2(), and so on. They can be members or extension functions, which lets you add destructuring to Java classes and other types you don't control:
import java.time.LocalDate
// a regular (non-data) class with operator componentN functions
class Rgb(private val packed: Int) {
operator fun component1() = (packed shr 16) and 0xFF
operator fun component2() = (packed shr 8) and 0xFF
operator fun component3() = packed and 0xFF
}
// extension functions add destructuring to classes you don't own
operator fun LocalDate.component1() = year
operator fun LocalDate.component2() = monthValue
operator fun LocalDate.component3() = dayOfMonth
operator fun StringBuilder.component1() = length
operator fun StringBuilder.component2() = toString()
fun main() {
val (r, g, b) = Rgb(0xFF8000)
println("r=$r g=$g b=$b")
val (year, month, day) = LocalDate.of(2026, 10, 17)
println("year=$year month=$month day=$day")
val (len, text) = StringBuilder("hello")
println("$len '$text'")
}
r=255 g=128 b=0
year=2026 month=10 day=17
5 'hello'
Rgb stores a packed integer, so destructuring isn't backed by properties at all: the component functions compute values on the fly. That's a good reason to write them by hand instead of using a data class.
Use extension components sparingly. LocalDate has an obvious order (year, month, day), but for most classes the order is arbitrary and a reader can't guess what val (a, b) = something returns. See operator functions for the other operators you can define.
Regex groups
MatchResult.destructured returns an object with component1() to component10(), one per capture group (group 0, the whole match, is skipped):
fun main() {
val re = Regex("""(\w+)@([\w.]+)""")
val match = re.find("contact: ann@example.com") ?: return
val (user, domain) = match.destructured
println("user=$user domain=$domain")
// destructured has component1()..component10() for groups 1..10
val log = listOf(
"2026-10-17 12:01:07 ERROR disk full",
"2026-10-17 12:01:09 INFO retrying",
)
val lineRe = Regex("""(\S+) (\S+) (\w+) (.*)""")
for (line in log) {
val (date, time, level, msg) = lineRe.matchEntire(line)!!.destructured
println("[$level] $msg at $time on $date")
}
// in a when branch
val cmd = "move 3 -2"
when (val m = Regex("""move (-?\d+) (-?\d+)""").matchEntire(cmd)) {
null -> println("unknown command")
else -> {
val (dx, dy) = m.destructured
println("dx=${dx.toInt()} dy=${dy.toInt()}")
}
}
}
user=ann domain=example.com
[ERROR] disk full at 12:01:07 on 2026-10-17
[INFO] retrying at 12:01:09 on 2026-10-17
dx=3 dy=-2
All components are Strings, so convert them as needed. For more about regular expressions see Introduction to regular expressions in Kotlin.
Nullable values
You can't destructure a nullable value directly:
data class User(val name: String, val email: String)
fun findUser(id: Int): User? = null
fun main() {
val (name, email) = findUser(1)
}
e2.kt:5:25: error: operator call 'component1()' cannot be applied to destructuring of nullable type 'User?'.
e2.kt:5:25: error: operator call 'component2()' cannot be applied to destructuring of nullable type 'User?'.
Handle the null first, with the Elvis operator or a safe call:
data class User(val name: String, val email: String)
fun findUser(id: Int): User? = if (id == 1) User("ann", "ann@example.com") else null
fun greet(id: Int) {
val (name, email) = findUser(id) ?: return println("user $id not found")
println("hello $name <$email>")
}
fun main() {
greet(1)
greet(2)
// or destructure inside let, which runs only for non-null values
findUser(1)?.let { (name, _) -> println("found $name") }
findUser(2)?.let { (name, _) -> println("found $name") }
// nullable components are fine
val (a, b) = Pair<String?, Int?>(null, 5)
println("a=$a b=$b")
}
hello ann <ann@example.com>
user 2 not found
found ann
a=null b=5
See Null safety for more about ?: and ?.let.
What destructuring can't do
Classic destructuring is deliberately limited. None of these compile:
data class Point(val x: Int, val y: Int)
data class Line(val from: Point, val to: Point)
val (gx, gy) = Point(0, 0)
class Shape {
val (w, h) = 10 to 20
}
fun main() {
var a = 1
var b = 2
(a, b) = b to a
val ((x1, y1), (x2, y2)) = Line(Point(0, 0), Point(3, 4))
}
e3.kt:4:5: error: syntax error: Destructuring declarations are only allowed for local variables/values.
e3.kt:7:9: error: syntax error: Destructuring declarations are only allowed for local variables/values.
e3.kt:13:7: error: syntax error: Expecting ')'.
...
e3.kt:15:5: error: initializer required for destructuring declaration.
...
- Only local variables. Top-level and class properties can't be declared with destructuring.
- No assignment to existing variables. Destructuring always declares new variables, so the Python-style swap
a, b = b, ahas no Kotlin equivalent. - No nesting. You can't unpack a component of a component in one declaration.
- No pattern matching. There's no destructuring in
whenbranches; match first, then destructure inside the branch, as in the regex example above.
The workarounds are straightforward:
data class Point(val x: Int, val y: Int)
data class Line(val from: Point, val to: Point)
fun main() {
// swap two variables without destructuring
var a = 1
var b = 2
a = b.also { b = a }
println("a=$a b=$b")
// nested values: destructure one level at a time
val line = Line(Point(0, 0), Point(3, 4))
val (from, to) = line
val (x1, y1) = from
val (x2, y2) = to
println("length=${Math.hypot((x2 - x1).toDouble(), (y2 - y1).toDouble())}")
// a map whose values are pairs
val ranges = mapOf("week" to (1 to 7), "month" to (1 to 31))
for ((name, range) in ranges) {
val (start, end) = range
println("$name: $start..$end")
}
}
a=2 b=1
length=5.0
week: 1..7
month: 1..31
a = b.also { b = a } works because b is evaluated first, then the lambda assigns the old a to b, and finally also returns the original b, which is assigned to a.
Position, not name: the coming change
Because destructuring is positional, val (end, start) = range silently swaps values if the names don't match the declaration order, and adding a property to the front of a data class silently breaks every caller that destructures it. Structs, tuples, and records shows this bug in detail.
Kotlin is moving to name-based destructuring. In Kotlin 2.4 it is experimental and enabled with a compiler flag. With -Xname-based-destructuring=complete:
(val a, val b) = xandval (a, b) = xmatch properties by name, in any order(val newName = property) = xrenames while destructuring- square brackets
val [a, b] = xmean positional destructuring throughcomponentN()
data class Range(val label: String, val start: Int, val end: Int)
fun main() {
val r = Range("week", 1, 7)
// name-based: matched by property name, order doesn't matter
(val end, val start) = r
println("start=$start end=$end")
// rename with =
(val from = start, val to = end) = r
println("$from..$to")
// positional, with square brackets
[val first, val second] = listOf("x", "y", "z")
println("$first $second")
// in a for loop and a lambda
val ranges = listOf(r, Range("month", 1, 31))
for ((val label, val end) in ranges) println("$label ends at $end")
ranges.forEach { (val start, val label) -> println("$label starts at $start") }
}
start=1 end=7
1..7
x y
week ends at 7
month ends at 31
week starts at 1
month starts at 1
Without the flag the compiler rejects the new syntax with the feature "name based destructuring" is only available since language version 2.5.
In complete mode a name that isn't a property is an error (unresolved reference 'begin' on receiver of type 'Range'), and so is old code like val (a, b) = "x" to "y", because Pair has properties first and second, not a and b. To prepare existing code, compile with -Xname-based-destructuring=name-mismatch. It keeps the old positional meaning but warns wherever a variable name differs from the property it reads:
n2.kt:5:10: warning: variable name 'end' differs from accessed property name 'label'. This syntax will be used for name-based destructuring in a future release, and this code will change its meaning.
Use the full name-based destructuring syntax '(val end = label, ...)', the new positional destructuring syntax '[end, ...]', or align the names to prepare for the transition.
Until the feature is stable, the safe habit is to keep destructured variable names identical to property names (val (key, value) = entry, val (first, second) = pair) or to use _. Code written that way means the same thing under both rules.
Summary
val (a, b) = xcallsx.component1()andx.component2(). Data classes,Pair,Triple,Map.Entry,IndexedValue, lists and arrays have them.- Destructure in
val/vardeclarations,forloops and lambda parameters:{ (k, v) -> ... }is one destructured parameter,{ k, v -> ... }is two parameters. - Use
_to skip a component; itscomponentN()isn't called. - Destructuring a list that's too short throws
IndexOutOfBoundsExceptionat runtime. - Add
operator fun componentN()as members or extensions to make any class destructurable. - Handle
nullbefore destructuring, with?: returnor?.let { (a, b) -> }. - Destructuring only declares new local variables: no properties, no nesting, no assignment to existing variables.
- It's positional today. Name-based destructuring is experimental in Kotlin 2.4; keep variable names equal to property names so your code survives the switch.