Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom getter for properties from type parameters

Tags:

kotlin

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?

like image 855
Farbod Salamat-Zadeh Avatar asked Sep 08 '16 16:09

Farbod Salamat-Zadeh


1 Answers

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"
}
like image 148
mfulton26 Avatar answered Sep 29 '22 03:09

mfulton26