【发布时间】:2017-08-14 15:05:39
【问题描述】:
我在 Kotlin 中创建了一个具有示例字段的类
class SomeClass {
var smth: String = "Initial value"
get() = "Here it is"
set(value) {
field = "it is $value"
}
}
当我创建类的对象并调用smth 字段时,它无论如何都会调用get() 属性。
val myValue = SomeClass().smth// myValue = "Here it is"
所以,问题是:为什么我们必须初始化一个有 getter 的字段?
var smth: String // Why this gives error?
get() = "Here it is"
set(value) {
field = "it is $value"
}
它总是会从get() 属性返回值,不是吗?
【问题讨论】:
-
这是因为 Kotlin 在使用
get() = ...没有任何初始化值时不会生成任何支持字段。例如:val smth: String get() = "Here it is"
标签: android class kotlin getter-setter