0

Since I have started to learn this language I've noticed that there are several ways to write a main method in order to run your code. What is the most used and best one?

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
g_rmz
  • 721
  • 2
  • 8
  • 20
  • Possible duplicate of [Difference between using App trait and main method in scala](http://stackoverflow.com/questions/11667630/difference-between-using-app-trait-and-main-method-in-scala) – FaigB Mar 09 '17 at 11:14

2 Answers2

3

This

object SO extends App {
    //Your main method's code goes here, since we have extended App
}

or

object SO {
  // here goes the main
  def main(args: Array[String]): Unit = {}
}

Personally I prefer the second one, as it distinguishes the main method more clearly.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Tawkir
  • 1,176
  • 7
  • 13
0

As per your question, in general to run code as executable are used :

With mixing App trait

object RunCode extends App {
   println("Execute here")
}

or concrete main method inside object

object RunCode {
    def main(args: Array[String]): Unit = {
        println("Execute here");
    }
}

The App trait is a convenient way of creating an executable Scala program. The difference to the main method alternative is that the App trait uses the delayed initialization feature.

FaigB
  • 2,271
  • 1
  • 13
  • 22