Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have functions that named componentN in Kotlin

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] ?

like image 464
icarumbas Avatar asked Dec 14 '22 19:12

icarumbas


1 Answers

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

like image 142
s1m0nw1 Avatar answered Dec 17 '22 22:12

s1m0nw1