I've just looked at Kotlin
standard library and found some strange extension-functions called componentN
where N is index from 1 to 5.
There are functions for all types of primitives. For example:
/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun IntArray.component1(): Int {
return get(0)
}
It looks curiously for me. I'm interested in developers motives. Is it better to call array.component1()
instead of array[0]
?
Kotlin has many functions enabling particular features by convention. You can identify those by the use of the operator
keyword. Examples are delegates, operator overload, index operator and also destructuring declarations.
The functions componentX
allow destructuring to be used on a particular class. You have to provide these functions in order to be able to destructure instances of that class into its components. It’s good to know that data
classes provide these for each of there properties by default.
Take a data class Person
:
data class Person(val name: String, val age: Int)
It will provide a componentX
function for each property so that you can destructure it like here:
val p = Person("Paul", 43)
println("First component: ${p.component1()} and second component: ${p.component2()}")
val (n,a) = p
println("Descructured: $n and $a")
//First component: Paul and second component: 43
//Descructured: Paul and 43
Also see this answer I gave in another thread:
https://stackoverflow.com/a/46207340/8073652
These are Destructuring Declarations and they're very convenient in certain cases.
val arr = arrayOf(1, 2, 3)
val (a1, a2, a3) = arr
print("$a1 $a2 $a3") // >> 1 2 3
val (a1, a2, a3) = arr
is compiled down to
val a1 = arr.component1()
val a2 = arr.component2()
val a3 = arr.component3()