Custom getter for type parameter properties

I have a Java file something like this:

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 more for my actual class, but the above example.

I want to write this in Kotlin, so I started with this:

class Thing(val property: String?)

Then I tried to implement a custom getter using the official documentation and another Kotlin question as a reference, for example:

class Thing(property: String?) {

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

}

However, my IDE (Android Studio) highlights the second one propertyon the third line of the above code in red and gives me a message:

The initializer is not allowed here because the property does not have a support field

Why am I getting this error and how can I write this custom getter as described above?

+4
1

"" "" get(), :

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

Source: https://habr.com/ru/post/1654045/


All Articles