正在初始化具有 getter 和 setter 的字段?
Initializing field that has getter and setter?
我创建了一个 class,它在 Kotlin 中有一个示例字段
class SomeClass {
var smth: String = "Initial value"
get() = "Here it is"
set(value) {
field = "it is $value"
}
}
当我创建 class 的对象并调用 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"
}
它总是 return 来自 get()
属性 的值,不是吗?
您在 setter 中有支持字段 field
,因此我们应该初始化,请参阅此 reference
我只是认为这是因为编译器不够聪明,无法推断它不为空。
实际上这里的官方文档提供了一个非常相似的代码 https://kotlinlang.org/docs/reference/properties.html
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // parses the string and assigns values to other properties
}
显然这段代码也不会编译,除非像
这样的构造函数
constructor(stringRepresentation: String) {
this.stringRepresentation = stringRepresentation
}
已添加。
我创建了一个 class,它在 Kotlin 中有一个示例字段
class SomeClass {
var smth: String = "Initial value"
get() = "Here it is"
set(value) {
field = "it is $value"
}
}
当我创建 class 的对象并调用 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"
}
它总是 return 来自 get()
属性 的值,不是吗?
您在 setter 中有支持字段 field
,因此我们应该初始化,请参阅此 reference
我只是认为这是因为编译器不够聪明,无法推断它不为空。
实际上这里的官方文档提供了一个非常相似的代码 https://kotlinlang.org/docs/reference/properties.html
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // parses the string and assigns values to other properties
}
显然这段代码也不会编译,除非像
这样的构造函数constructor(stringRepresentation: String) {
this.stringRepresentation = stringRepresentation
}
已添加。