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]
?
These are Destructuring Declarations and they're very convenient in certain cases.
is compiled down to
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 thatdata
classes provide these for each of there properties by default.Take a data class
Person
:It will provide a
componentX
function for each property so that you can destructure it like here:Also see this answer I gave in another thread:
https://stackoverflow.com/a/46207340/8073652