As I was learning Scala 3, I saw a new way to write main:
@main def main1 =
println("main1 printed something")
I checked source for @main, it is just
class main extends scala.annotation.Annotation {}
What is happening by using @main here?
@main isn't really doing anything. It's the Scala compiler which does everything. Scala compiler will look for any methods which are marked with @main and turn them into java (jvm) entry static void main method.
Scala also supports multiple @main . It will link every @main method to a single static void method in a different class.
Besides wiring @main method to a java entrypoint, Scala compiler also adds some basic argument parsing. For example , you could do:
@main def go(name:String, age:Int) = println(s"hello, $name ($age)")
and expect it to work via CLI when you pass the name and age.
So @main is just really a marker annotation.
Reference documentation: https://dotty.epfl.ch/docs/reference/changed-features/main-functions.html
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