kotlin中有一个数据类,例如.

@Entity
data class Record(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = null,
    @Column(nullable = false, name = "name")
    var name: String? = null
)

And I can call component1 and component2 functions to access the properties. However, as I declare the property var, I have getter and setter, and if I declare property val I have the getter. Are componentN functions are redundant in this case, and why do we need them, because getters seem to be much more self-explanatory?

推荐答案

Kotlin通过componentN个函数支持以下语法:

val (name, age) = person 

这种语法称为destructuring declaration.析构声明一次创建多个变量.我们声明了两个新变量:name和age.

A destructuring declaration is compiled down to the following code:

val name = person.component1()
val age = person.component2()

the component1() and component2() functions are another example of the principle of conventions widely used in Kotlin (see operators like + and *, for-loops etc.). Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it. And, of course, there can be component3() and component4() and so on.

Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.

Kotlin相关问答推荐

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

Kotlin中函数引用的否定

"Kotlin中的表达式

Kotlin Poet 的导入不明确

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

Kotlin 函数有 2 个参数用于对 Map 或 List 进行排序

循环中的每个元素都应填充行中可用的所有可用空间

为什么 Kotlin 在 sumOf 函数 lambda 中默认不将数字视为Int?

为什么 KFunction2 在 Kotlin 中不是可表示类型?

基类中的 ViewModelProviders.get(...)

Koin Android:org.koin.error.NoBeanDefFoundException

从列表中的每个对象中 Select 属性

Kotlin 中的 Java Scanner 相当于什么?

如何在 Kotlin 中判断数组类型(不是泛型类型)

Kotlin 创建snackbar

Dagger2 Qualifier 不适用于 Kotlin?

Kotlin内联扩展属性

Kotlin的web-framework框架

Kotlin 的数据类 == C# 的 struct ?

在 intelliJ 元素中集成 Kotlinx 协程