Quick question, why is this allowed: ``` class A(...
# announcements
j
Quick question, why is this allowed:
Copy code
class A(b: String){
    var b: String

    init{
        this.b = b
    }
}
but when you add a setter, the property needs to be initialized, otherwise it doesn't compile?
Copy code
class A(b: String){

    var b: String  // <- b needs to be inialized, otherwise no compile
    set(value) {field = value}

    init{
        this.b = b
    }
}
+ @ijp @ndv
d
Because the setter might not actually set the underlying field. So if you have a custom setter, you must provide an initial value, so that the field can never hold "no value" (i.e.
null
).
The field initializer does not use the setter, to be clear.
j
but the init is actually setting the value, so doesn't that guarantee that it's initialized ?
n
init is using the setter
i
@janvladimirmostert init is calling the setter
m
Init calls the setter, which isn't guaranteed to set the value.
j
fair enough
i
why is nullable scenario handled the same though?
Copy code
class A(b: String){

    var b: String?  // <- b needs to be inialized, otherwise no compile
    set(value) {field = value}

    init{
        this.b = b
    }
}
in this case field can hold null value
d
Yes, but if you want that, you need to be explicit about it. Things in Kotlin don't happen unless you tell them to happen. If you want null in the field, you need to put it there.
m
Null is not the same as "no value"
j
null != uninitialized
i
sure, I understand
thanks
j
is it possible in this scenario to declare b as
lateinit
in some way ? Doesn't seem like it
d
No,
lateinit
does not allow custom setters.