Joshua Hansen
01/13/2025, 7:15 AMfoo
is null in the init of the Parent
class. test
fails to initialize due to NullPointerException. Why? How do I get around this? In my actual code, foo
is actually being overridden to be a particular subclass. But in this example, I'm just using String. Overriding is necessary here.
fun main() {
val test = Child()
}
open class Parent(
open val foo: String = "Hello",
) {
init {
println(foo.length)
}
}
class Child(
override val foo: String = "World",
) : Parent(foo)
Sam
01/13/2025, 8:39 AMinit
block in your Parent
class runs before Child.foo
has been assigned a value. Even though foo
is non-nullable, it will still temporarily appear to be null if accessed before initialization.Sam
01/13/2025, 8:39 AMephemient
01/13/2025, 8:46 AMopen class Parent(
val foo: String = "Hello",
) {
init {
println(foo.length)
}
}
class Child(
foo: String = "World",
) : Parent(foo)
which does not have any use before initializationJoshua Hansen
01/13/2025, 7:45 PMephemient
01/13/2025, 7:48 PMinterface Base {
val foo: String
}
class One(override val foo: String = "Hello") : Base
class Two(override val foo: String = "World") : Base
ephemient
01/13/2025, 7:53 PMopen val
+ override val
is usually a bad idea. you end up with an inaccessible backing field in the base class which is shadowed