Skip to Content

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.

/wp-content/uploads/2015/12/clipboard1_845533.png

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?

/wp-content/uploads/2015/12/clipboard2_845534.png

Check the bytecode generated after this sample scala program is compiled and we can find the following useful points:

/wp-content/uploads/2015/12/clipboard3_845535.png

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.

/wp-content/uploads/2015/12/clipboard4_845536.png


(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()); }

/wp-content/uploads/2015/12/clipboard5_845537.png

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.

/wp-content/uploads/2015/12/clipboard6_845538.png

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.

/wp-content/uploads/2015/12/clipboard7_845539.png

You can also find how those compiled Java class methods are called in the runtime in the debugger.

/wp-content/uploads/2015/12/clipboard8_845540.png

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply