Farbod Salamat-Zadeh
Farbod Salamat-Zadeh

Reputation: 20140

Custom getter for properties from type parameters

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?

Upvotes: 16

Views: 11829

Answers (1)

mfulton26
mfulton26

Reputation: 31274

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"
}

Upvotes: 23

Related Questions