从类型参数中为属性定制getter

时间:2016-09-08 16:38:11

标签: kotlin

我有一个类似的Java文件:

public class Thing {

    private String property;

    public Thing(String property) {
        this.property = property;
    }

    public String getProperty() {
        if (property == null) {
            return "blah blah blah";
        } else {
            return property;
        }
    }

}

显然我的实际课程还有更多,但上面只是一个例子。

我想在Kotlin写这个,所以我从这开始:

class Thing(val property: String?)

然后我尝试使用the official documentationanother Kotlin question作为参考来实现自定义getter,如下所示:

class Thing(property: String?) {

    val property: String? = property
        get() = property ?: "blah blah blah"

}

但是,我的IDE(Android Studio)以红色突出显示上述代码第3行的第二个property并给我提供消息:

  

此处不允许使用初始化程序,因为该属性没有后备字段

为什么我会收到此错误,如何能够如上所述编写此自定义getter?

1 个答案:

答案 0 :(得分:10)

您需要在get()的正文中使用“字段”而不是“属性”才能声明backing field

class Thing(property: String?) {
    val property: String? = property
        get() = field ?: "blah blah blah"
}

但是,在这个特定示例中,使用非null属性声明可能会更好:

class Thing(property: String?) {
    val property: String = property ?: "blah blah blah"
}