https://kotlinlang.org logo
#announcements
Title
# announcements
j

janvladimirmostert

09/08/2017, 10:37 AM
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

diesieben07

09/08/2017, 10:40 AM
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

janvladimirmostert

09/08/2017, 10:41 AM
but the init is actually setting the value, so doesn't that guarantee that it's initialized ?
n

ndv

09/08/2017, 10:41 AM
init is using the setter
i

ijp

09/08/2017, 10:41 AM
@janvladimirmostert init is calling the setter
m

marstran

09/08/2017, 10:41 AM
Init calls the setter, which isn't guaranteed to set the value.
j

janvladimirmostert

09/08/2017, 10:41 AM
fair enough
i

ijp

09/08/2017, 10:42 AM
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

diesieben07

09/08/2017, 10:43 AM
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

marstran

09/08/2017, 10:43 AM
Null is not the same as "no value"
j

janvladimirmostert

09/08/2017, 10:43 AM
null != uninitialized
i

ijp

09/08/2017, 10:43 AM
sure, I understand
thanks
j

janvladimirmostert

09/08/2017, 10:45 AM
is it possible in this scenario to declare b as
lateinit
in some way ? Doesn't seem like it
d

diesieben07

09/08/2017, 10:56 AM
No,
lateinit
does not allow custom setters.
2 Views