kotlinpropertiesinitializationvar

In Kotlin, does the presence of a custom setter affect the necessity of initializing a var property?


class Student (private val age: Int){
    var isAdultA
        get() = this.age >= 20
        set(value) {}

    var isAdultB // "Property must be initialized"
        get() = this.age >= 20
}

Hello, I've encountered a situation where isAdultA compiles without any issues, but isAdultB gives an "Property must be initialized" error message. While I'm aware that isAdultB hasn't explicitly defined a setter, I understand that a default setter is automatically generated. What fundamentally sets apart isAdultA and isAdultB? Why is isAdultA viable while isAdultB isn't?

I would appreciate any assistance. Thank you.


Solution

  • If we use default implementation of accessors, then the compiler generates a backing field for us and gets/sets this field. In your example, the compiler generates isAdultB field and then the setAdultB() method sets the value of this field. isAdultB is never read anywhere. And because we have a field, we have to initialize it to some value.

    On the other hand, isAdultA doesn't require to generate any field at all, so we don't have to initialize it.