The main() Method in Scala
This tutorial will discuss the main()
method and its uses in Scala. The main()
method is Scala’s code execution entry point.
It is similar to the main of C, C++, and Java. As the name implies, this method is the main entry point for executing any Scala code.
Syntax:
def main(args: Array[String]): Unit = {
// main method body
}
Here, the def
is a keyword that is used to define a function, the main
is the function name, and (args: Array[String])
is about method arguments that tell the compiler what type of argument it can accept during the call. The args
is an array of strings.
The Unit =
is a keyword used to define a function that does not return anything. It is similar to the void keyword in C and Java languages.
the main()
Method in Scala
This is the simplest example of Scala’s main()
method. In the example below, we just put a single print statement to print a message on the console.
Code:
object MyClass {
def main(args: Array[String]) : Unit = {
print("hello from the main method")
}
}
Output:
hello from the main method
If you modify its return type or signature, you get the compile-time error as stated in the output below. So never modify the main method signature and use it as it is.
Code:
object MyClass {
def main(args: Array[String]) : Int = {
print("hello from the main method")
return 12
}
}
Output:
hello from the main method
app.scala:3: warning: not a valid main method for Main,
because main methods must have the exact signature `(Array[String]): Unit`, Scala runners will forgive a non-Unit result.
To define an entry point, please define the main method as:
def main(args: Array[String]): Unit
def main(args: Array[String]) : Int = {
^
the @main
Annotation in Scala
If you are working with Scala 3, then you can use the @main
annotation to create the main method or mark any method as the main method. The Scala provides a new annotation that can make your function an entry point of execution, and you’ll get the same result as the above example.
Code:
object MyClass {
@main
def helloWorld() = println("hello from the main method")
}
Output:
hello from the main method
Decompiled the Scala Code Into the Java
If you wish to see the internal code of Scala, you can do it by decompiling the Scala class. We did the same thing and got the same code in Java.
We can now run this code to any JVM machine.
Code:
Compiled from "MyClass.scala"
public final class MyClass {
public static void main(java.lang.String[]);
}