So I read that the App trait has the following fields:
def delayedInit(body: ⇒ Unit): Unit
val executionStart: Long
def main(args: Array[String]): Unit
I know that if a trait only has one method, by "putting code" between the curly braces in the class declaration I am overriding that. But here I have two methods. So why am I overriding automatically main and not delayedInit?
trait App extends DelayedInitNo explicit main method is needed. Instead, the whole class body becomes the “main method”. args returns the current command line arguments as an array.
When a class inherits from another, it may want to modify the definition for a method of the superclass or provide a new version of it. This is the concept of Scala method overriding and we use the 'override' modifier to implement this.
App is a trait which is utilized to rapidly change objects into feasible programs, which is carried out by applying DelayedInit function and the objects inheriting the trait App uses this function to execute the entire body of the program as a section of an inherited main method.
When a subclass has the same name method as defined in the parent class, it is known as method overriding. When subclass wants to provide a specific implementation for the method defined in the parent class, it overrides method from parent class.
You are not overriding main
method.
Since App
extends DelayedInit
compiler rewrites your code like this:
// Before:
object Test extends App {
println("test")
}
// After:
object Test extends App {
delayedInit{println("test")}
}
From DelayedInit
documentation:
Classes and objects (but note, not traits) inheriting the
DelayedInit
marker trait will have their initialization code rewritten as follows:code
becomesdelayedInit(code)
.
App
trait implements delayedInit
like this:
override def delayedInit(body: => Unit) {
initCode += (() => body)
}
So in Test
object constructor code println("test")
is stored as function (() => Unit
) in initCode
field.
main
method of App
is implemented as call for all functions stored in initCode
field:
for (proc <- initCode) proc()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With