liveBook · Manning

componentN function

As explained in Kotlin in Action, 2E

A componentN function is a Kotlin convention-named function that returns the Nth component of a composite value for use in a destructuring declaration.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains compiler-generated and manually defined componentN functions, positional binding, ignored values, and refactoring risks.
Examples
Demonstrates Point, filename splitting with NameComponents, collection destructuring, and selective Person destructuring.
What it assumes
Assumes familiarity with Kotlin conventions and data classes while teaching destructuring mechanics from concrete examples.
What you can do after
Apply componentN functions to build destructurable classes and unpack data-class, collection, and function-return values.
How it connects
Connects destructuring declarations with data classes, collections, arrays, Pair, and Triple.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.