- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 105字
- 2021-06-24 19:15:25
Destructuring methods
By convention, any instance of a class that has a series of methods named component1(), component2() and so on can be used in a destructuring declaration.
Kotlin will generate these methods for any data class:
val (prod: BakeryGood, price: Double, qty: Int) = mySecondItem
The prod value is initialized with the return of component1(), price with the return of component2() , and so on. Although the preceding example use explicit types, those aren't needed:
val (prod, price, qty) = mySecondItem
In some circumstances, not all values are needed. All unused values can be replaced by (_):
val (prod, _, qty) = mySecondItem