【问题标题】:Difference between accessing via dot notation and destructuring in kotlin data class在 kotlin 数据类中通过点符号访问和解构之间的区别
【发布时间】:2022-11-22 23:16:17
【问题描述】:

我有一个像这样的data class

data class Task(
    var id: Int,
    var description: String,
    var priority: Int
)

我实现它如下

val foo = Task(1, "whatever", 10)

我读到过像这样访问whatever

foo.description

或者

foo.component2()

有什么区别?

【问题讨论】:

  • 实际上,您自己从不使用component2()。这只是使解构成为可能的必要条件
  • 为什么你会通过明确调用component2来访问descriptioncomponent2 应该在您使用解构语法时被隐式调用。

标签: kotlin


【解决方案1】:

行为没有区别,但使用foo.description

直接使用 componentN() 函数是极其罕见的。如果您知道您正在访问哪个组件,那么直接使用该属性会更具可读性。

componentN() 函数主要是实现实际解​​构声明的工具,例如:

val (id, desc, prio) = task

这是一个快捷方式,相当于:

val id = task.component1()
val desc = task.component2()
val prio = task.component3()

..你可能永远不应该在源代码中编写它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2016-01-04
    • 2021-01-17
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多