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?
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.
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 .
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.
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)
}
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