Constructor in Scala
Note: This blog is written based on Scala 2.11.7.
Any codes directly written in the class implementation in Scala will be considered as constructor code, for example below.
When an instance of test is created, the constructor is called. Nothing new compared with Java and ABAP so far.
However, if we modify class test a little bit, to make it extend from App, then after an instance is created, constructor code is not called at all. Why?
Check the bytecode generated after this sample scala program is compiled and we can find the following useful points:
1. In the constructor of test class, there is no code to print out Hello World, which explain the reason why we see nothing when a new instance of test is created.
2. Instead, the Hello World string will be printed out in another public method of class: delayedEndpoint$blog$test$1(). It will be called by an inner class delayedInit$body, method apply(). The method name here is interesting since in Scala we can also explicitly call apply method on any function to execute it.
3. The code in test constructor simply calls the function delayedInit provided in App implementation:
(a) Each App instance has a internal ListBuffer which has a line type of a function with no input argument and no return value.
The delayedInit function simply accepts a function with such type and append it to the ListBuffer and that’s all.
(b) Back to our example, our constructor code contained in Java method delayedEndpoint$blog$test$1(), which is actually the body of function delayedInit$body, which is appended to the ListBuffer via the code in Test constructor code: delayedInit(new delayedInit.body()); }
In the implementation of App, we can also find there is one method main, where the ListBuffer is looped and each function within it is executed one by one. This gives us a hint: our constructor will be executed, once we explicitly call main method on the created app instance. Let’s verify it.
It works as expected. We can also find in the debugger that in the runtime, there is indeed one entry in ListBuffer, which contains our Hello World printing code.
You can also find how those compiled Java class methods are called in the runtime in the debugger.