postDerivedInit{} in open class

Derived classes are initialized after their base. Most of the time it make sence.

But it would be great if there were a place to do post initialize things after initialization of all derived clases are done.

open class A {
    dosomething() // error!!  inherited are not initialized
    dosomething() // ok!

  open fun dosomething() {}

open class B(val some:Some):A(){
 override fun dosomething(){ some.dosomething()  }   // some can be null !

The general solution to all init problems is not to use init at all (use it only for very simple parameter initialization as it is intended to). It is vulnerable to a lot of mistakes. If you have some kind of complicated initialization logic, try to replace it with protected constructor + factory function.

1 Like

protected constructor + factory is just one of workaround with itsown downsides and errorprones

Among “Many mistakes” for init I can remember only “leak reference” to not fully constructed object.

Suggested “postDerivedInit” will also greatly decrease severity of such mistake

Java is full of factories. They’re mechanical, repetitive, typically untested and sometimes the source of subtle bugs.