Why, if I extend the App feature in Scala, do I override the main method?

So, I read that the application property has the following fields:

def delayedInit(body: β‡’ Unit): Unit val executionStart: Long def main(args: Array[String]): Unit 

I know that if a trait has only one method, β€œputting code” between curly braces in a class declaration, I override this. But here I have two methods. So why do I automatically override main and not delayedInit?

+7
scala
source share
1 answer

You do not override the main method.

Since the App extends DelayedInit compiler overwrites your code as follows:

 // Before: object Test extends App { println("test") } // After: object Test extends App { delayedInit{println("test")} } 

From the DelayedInit documentation :

Classes and objects (but note, not traits) inheriting The DelayedInit marker DelayedInit will have its initialization code rewritten as follows: code becomes delayedInit(code) .

App trait implements DelayedInit as follows:

 override def delayedInit(body: => Unit) { initCode += (() => body) } 

So, in Test code of the constructor for println("test") is stored as a function ( () => Unit ) in the initCode field.

main App method is implemented as a call to all functions stored in the initCode field:

 for (proc <- initCode) proc() 
+10
source share

All Articles