【问题标题】:Why do we have functions that named componentN in Kotlin为什么我们在 Kotlin 中有名为 componentN 的函数
【发布时间】:2017-12-26 12:54:29
【问题描述】:

我刚刚查看了Kotlinstandard library,发现了一些名为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]更好吗?

【问题讨论】:

    标签: arrays kotlin kotlin-extension


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      这些是Destructuring Declarations,在某些情况下它们非常方便。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        • 2011-04-22
        • 2019-06-27
        • 2016-10-19
        • 2011-02-04
        相关资源
        最近更新 更多