Why do we have functions that named componentN in Kotlin

牧云@^-^@ 提交于 2019-12-31 00:04:14

问题


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


回答1:


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




回答2:


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()


来源:https://stackoverflow.com/questions/47978945/why-do-we-have-functions-that-named-componentn-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!