我有一个类似的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 documentation和another Kotlin question作为参考来实现自定义getter,如下所示:
class Thing(property: String?) {
val property: String? = property
get() = property ?: "blah blah blah"
}
但是,我的IDE(Android Studio)以红色突出显示上述代码第3行的第二个property
并给我提供消息:
此处不允许使用初始化程序,因为该属性没有后备字段
为什么我会收到此错误,如何能够如上所述编写此自定义getter?
答案 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"
}