And you thought the App trait is just a convenient way of creating an executable Scala program

Reading Time: 3 minutes

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.

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

Written by 

Rachel Jones is a Solutions Lead at Knoldus Inc. having more than 22 years of experience. Rachel likes to delve deeper into the field of AI(Artificial Intelligence) and deep learning. She loves challenges and motivating people, also loves to read novels by Dan Brown. Rachel has problem solving, management and leadership skills moreover, she is familiar with programming languages such as Java, Scala, C++ & Html.

1 thought on “And you thought the App trait is just a convenient way of creating an executable Scala program3 min read

Comments are closed.