How does the @main annotation in Scala 3 w​ork?

Viewed 463

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?

1 Answers

@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

Related