为什么我们在Kotlin中有名为componentN的函数

ica*_*bas 4 arrays kotlin kotlin-extension

我刚看了Kotlin 标准库,发现了一些奇怪的扩展函数componentN ,其中N是从1到5的索引.

所有类型的基元都有函数.例如:

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

它对我来说很奇怪.我对开发者的动机很感兴趣.打电话array.component1() 而不是array[0]

s1m*_*nw1 8

Kotlin具有许多按惯例实现特定功能的功能.您可以通过使用operator关键字来识别它们.例如委托,运算符重载,索引运算符以及解构声明.

这些函数componentX允许在特定类中使用解构.您必须提供这些函数才能将该类的实例解构为其组件.很高兴知道data默认情况下类为每个属性提供这些属性.

拿一个数据类Person:

data class Person(val name: String, val age: Int)
Run Code Online (Sandbox Code Playgroud)

它将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
Run Code Online (Sandbox Code Playgroud)

另见我在另一个帖子中给出的答案:

/sf/answers/3234513831/


Ale*_*nov 7

这些是解构声明,在某些情况下非常方便。

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

print("$a1 $a2 $a3") // >> 1 2 3
Run Code Online (Sandbox Code Playgroud)
val (a1, a2, a3) = arr
Run Code Online (Sandbox Code Playgroud)

编译为

val a1 = arr.component1()
val a2 = arr.component2()
val a3 = arr.component3()
Run Code Online (Sandbox Code Playgroud)