Kotlin: why do I need to initialize a var with custom getter?

Reason behind this is Backing field. When you create val with custom getter that does not use field identifier to access its value, then backing field is not generated.

val greeting: String
    get() = "hello"

If you do, then backing field is generated and needs to be initialized.

val greeting: String // Property must be initialized
    get() = field

Now with var. Since backing filed is generated by default, it must be initialized.

var greeting: String // Property must be initialized
    get() = "hello"

For this to work for var without initialization, you must provide a custom setter to prevent generation of backing field. For example:

var storage: String = ""
var greeting: String
    get() = "hello"
    set(value) { storage = value}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)