【问题标题】:Initializing field that has getter and setter?初始化具有 getter 和 setter 的字段?
【发布时间】: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


【解决方案1】:

你在setter中有支持字段field,所以我们应该初始化,看这个reference

【讨论】:

    【解决方案2】:

    我只是认为这是因为编译器不够聪明,无法推断它不为空。

    实际上,这里的官方文档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
    }
    

    已添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多