Reputation: 4117
I have a property with a getter, default setter and no initializer like this:
var test: String
get() = "test value"
private set
If I try this code in Android studio I get a compile error stating that Property must be initialized
. If I instead try it at try.kotlinlang.org the code runs fine and test value
is returned whenever I access the property.
I'm trying to read the Kotlin documentation for properties, but I can't really tell if this is supposed to work or not.
Is this valid Kotlin code or not?
Upvotes: 3
Views: 398
Reputation: 39843
The try.kotlinlang.org also accepts an uninitialized val
returning null
though it is non-nullable:
var test: String
private set
Your intent is possible if you make the var
not field-backed at all:
var test: String
get() = "test value"
private set(value) = Unit
For the Backing Fields the documentation states:
A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the
field
identifier.
Upvotes: 4