Scala: how to complete a subclass constructor?

in scala, I have a base class and several child classes. without adding code to the child class or without changing the instance of the child class, I would like the base class to be able to call some code both before and after the child constructor is executed. it was easy before, since the constructor of the base class is called before the child, but I see no way to handle the case after. as a little example code:

class A { // do some stuff before child constructor is called // ... // do some other stuff after child constructor is called // this could be a method or inline in the constructor, doesn't matter. } class B extends A { // stuff happens in between } class C extends A { // stuff happens in between } etc val b = new B // everything happens inside, no other method call needed 

Is this possible? thanks.

+4
source share
2 answers

If you are using Scala 2.9, you can arrange something like this:

 class A { println("Hi") } class B extends A with DelayedInit { private[this] var count = 0 println("Hey") def delayedInit(x: => Unit) { x count += 1 if (count==2) { println("There") } } } class C extends B { println("Ho") } class D extends C { println("Ha") } 

This uses the new DelayedInit attribute, which sends the deferred constructors from the current and all child classes to the DelayedInit method. Unfortunately, since there is no completion signal, you are limited to skipping one constructor. So, for C we get:

 scala> new C Hi Hey Ho There 

where the block "There" magically appeared after the block "Ho" from C Unfortunately, if you extend C , the new initialization happens last:

 scala> new D Hi Hey Ho There Ha 

(You really don't need A there ... I just put it there to illustrate what happens to superclasses.)

+4
source

possible answer is "end of a specific class", the code below:

 hello world1 world2 world3 end of the worlds ! trait A extends DelayedInit { def delayedInit(body: => Unit) = { body println("end of the worlds !") } } trait B extends A { println("hello") } trait C extends B { println("world1") } trait D extends C { println("world2") } object Zozo extends D { println("world3") } 
0
source

All Articles