Why do we have functions that called componentN in Kotlin

I just looked through the standard library Kotlin and found some weird extension functions called componentNwhere N is an index from 1 to 5.

There are functions for all types of primitives. For instance:

/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun IntArray.component1(): Int {
    return get(0)
}

I'm curious about that. I'm interested in the motives of the developers. Is it better to call array.component1()instead array[0]?

+4
source share
2 answers

Kotlin , . operator. , , , .

componentX . , . , data .

Person:

data class Person(val name: String, val age: Int)

componentX , , :

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

. , :

fooobar.com/questions/1271765/...

+7

, .

val arr = arrayOf(1, 2, 3)
val (a1, a2, a3) = arr

print("$a1 $a2 $a3") // >> 1 2 3

val (a1, a2, a3) = arr

val a1 = arr.component1()
val a2 = arr.component2()
val a3 = arr.component3()
+3

Source: https://habr.com/ru/post/1691348/


All Articles