Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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?

like image 920
gotch4 Avatar asked Nov 06 '13 09:11

gotch4


People also ask

What does extends App do in Scala?

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 to use override in Scala?

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.

How does Scala app trait work?

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.

What is method overriding in Scala?

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.


1 Answers

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 becomes delayedInit(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()
like image 190
senia Avatar answered Oct 14 '22 01:10

senia