class C(val string: String) {
init {
println(string)
}
}
abstract class A {
abstract var string: String
val c = C(string)
}
class B : A() {
override var string = "string"
}
fun main() {
B()
}
kotlin playground for the problem
This code crash in runtime due to string var not initialized, how to do it right?
>Solution :
It’s not a good practice and dangerous to use an abstract or open variable in the initialization of your class. And if you write this code in Android Studio or IntelliJ IDEA you will get this warning: Accessing non-final property string in constructor.
So what’s happening here ? Well the super class which is A is going to be initialized first before totally initializing B, so this line of code val c = C(string) is going to run before even giving a value to string and that’s what causing the error and you will get a NullPointerException because string is null.
How to fix this ? You can use lazy to initialize c like that:
val c by lazy { C(string) }
Now c is not going to be initialized only if you call it, so now it’s safe
because you can’t call it only if B is fully initialized.