Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 314
Dave Prateek Avatar asked Jan 25 '23 07:01

Dave Prateek


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

like image 138
Bilal Fazlani Avatar answered Jan 30 '23 01:01

Bilal Fazlani