A componentN function is a convention-named Kotlin function that returns the Nth component of a composite value. Destructuring declarations call component1(), component2(), and subsequent functions by position to initialize separate variables. Data classes receive these functions automatically for each primary-constructor property. section 9.4
fun main() {
val p = Point(10, 20)
val (x, y) = p #1
println(x)
// 10
println(y)
// 20
}
A destructuring declaration unpacks a Point by calling its component functions, assigning 10 to x and 20 to y. section 9.4
A regular class can support destructuring by defining component functions manually, typically with operator fun. The function number determines the variable position, not the variable name, so val (x, y) = point uses component1() for x and component2() for y. section 9.4
Returning multiple values
A data class can package a filename’s name and extension, while destructuring makes the result convenient to consume: val (name, ext) = splitFilename("example.kt"). The same convention also works with arrays and collections, including the first five elements supported by the standard library. section 9.4
Use componentN functions carefully:
- Use _ for an unused position; removing a middle variable shifts later assignments because calls remain positional. section 9.4.2
- Prefer destructuring for small, stable container classes such as key-value or index-value pairs; reordering data-class properties can silently change assignments. section 9.4.2
