5

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

所有类型的原语都有函数。例如:

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

它看起来对我来说很奇怪。我对开发人员的动机感兴趣。array.component1() 打电话而不是打电话更好array[0]吗?

4

2 回答 2

9

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

另请参阅我在另一个线程中给出的答案:

https://stackoverflow.com/a/46207340/8073652

于 2017-12-26T14:00:28.263 回答
6

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

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()
于 2017-12-26T12:59:10.027 回答