Ok, Let’s start discussion about the App trait uses in our code segment. Here I will try to demonstrate some use cases for the better use of App trait in our Scala code. To read more about the App trait you can refer to the documentation here
Let’s go with our daily uses of App trait 🙂
Just want to print something on console:
In the code above, we are inheriting the main method of App. We can do this also to print the same:
Output for the both : Hello Scala!
Now let’s try in advance way:
What do you think is going to be the output of this code block? If you answered
world! you are not correct. Because the output is Welcome to SCALA world!
Nothing special in above code block. I have just overridden the delayedInit method of DelayedInit marker trait. This method is normally never called directly from user code. Instead it is called as compiler-generated code for those classes and objects (but not traits) that inherit from the `DelayedInit` trait and that do not themselves define a `delayedInit` method.
Let us look at a good case of using DelayedInit marker trait with App trait. We want to execute a list of the methods before the object MainApp executable block.
Output: 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50 10 / 5 = 2 WOW: All methods have been executed successfully!
Why it’s happening?
The initialization code of an object or class (but not a trait) that follows the superclass constructor invocation and the mixin-evaluation of the template’s base classes is passed to a special hook, which is inaccessible from user code. Normally, that hook simply executes the code that is passed to it. But templates inheriting the scala.DelayedInit trait can override the hook by re-implementing the delayedInit method. So all this involves a bit of magic. The App trait extends another trait, DelayedInit, that gets special handling from the compiler. All initialization code of a class with that trait is moved into delayedInit method. The main of the App trait method captures the command line arguments, calls the overridden delayedInit method, and executes the our code block.
Note: In Future versions of App trait will no longer extend DelayedInit
. Scala will introduce OnCreate trait: call onCreate method after object creation with DelayedInit
Reblogged this on Play!ng with Scala and commented:
Scala App trait with DelayedInit.