Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala main returns unit. How to set program's return value

Tags:

scala

The method prototype for main is:

def main(args: Array[String]): Unit

Typically, an application needs to specify a return code when it exits. How is that typically done in scala if main returns Unit? Should I call System.exit(n)?

Also, the docs warn that I should not use main at all, though this seems at odds with the getting started guide).

What's the best practice here?

like image 265
user48956 Avatar asked Dec 27 '13 16:12

user48956


People also ask

How do you declare a main function in Scala?

def main(args: Array[String]): def is the keyword in Scala which is used to define the function and “main” is the name of Main Method. args: Array[String] are used for the command line arguments. println(“Hello World!”): println is a method in Scala which is used to display the Output on console.

Can a Scala class have main method?

The Scala compiler generates a program from an @main method f as follows: It creates a class named f in the package where the @main method was found. The class has a static method main with the usual signature of a Java main method: it takes an Array[String] as argument and returns Unit .

How do you exit a Scala code?

exit(n) or better sys. exit(n) (which is Scala's equivalent). If you mix in App in your main application object, you do not define method main but can just write its contents in the object's body directly.


1 Answers

Yes, you exit with a code different than zero by calling either java.lang.System.exit(n) or better sys.exit(n) (which is Scala's equivalent).

If you mix in App in your main application object, you do not define method main but can just write its contents in the object's body directly.

E.g.

object Test extends App {
  val a0 = args.headOption.getOrElse {
    Console.err.println("Need an argument")
    sys.exit(1)
  }
  println("Yo " + a0)
  // implicit: sys.exit(0)
}
like image 50
0__ Avatar answered Sep 30 '22 07:09

0__