In Scala, what is an “early initializer”?

Early initializers are part of the constructor of a subclass that is intended to run before its superclass. For example:

abstract class X {
    val name: String
    val size = name.size
}

class Y extends {
    val name = "class Y"
} with X

If the code was written instead as

class Z extends X {
    val name = "class Z"
}

then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class).

Leave a Comment