I have a Java file a little like so:
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;
}
}
}
Obviously there's more to my actual class but the above is just an example.
I want to write this in Kotlin, so I started with this:
class Thing(val property: String?)
Then I tried to implement the custom getter using the official documentation and another Kotlin question as reference, like this:
class Thing(property: String?) {
val property: String? = property
get() = property ?: "blah blah blah"
}
However, my IDE (Android Studio) highlights the second property
on the 3rd line of the above code in red and gives me the message:
Initializer is not allowed here because the property has no backing field
Why am I getting this error, and how would I be able to write this custom getter as described above?
You need to use "field" instead of "property" in the body of your get()
in order to declare a backing field:
class Thing(property: String?) {
val property: String? = property
get() = field ?: "blah blah blah"
}
However, in this particular example you might be better off with a non-null property declaration:
class Thing(property: String?) {
val property: String = property ?: "blah blah blah"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With