Search code examples
scalascala-3

default values ignored in @main?


In Scala 3 I can specify a main method which gets one parameter like this:

@main def main(mode: String): Unit = ???

If I run it without specifying the argument, I would get “Illegal command line: more arguments expected”. Fine.

Now if I specify a default value like this

@main def main(mode: String = "foo"): Unit = ???

then I still get that same error.

  1. Why is that?
  2. And why doesn't the compiler complain if default values are not possible in main method arguments? To just ignore them doesn't seem useful to me.

Tried with Scala 3.4.2.

Edit: submitted https://github.com/scala/scala3/issues/20485


Solution

  • Scala 3 main method parameters are good only for very basic cases, examples and such. For any real use be sure to use a dedicated library. There probably exist other, but the best known is mainargs. The current Scala 3 implementation is a subset of this library. See also Plan for @main and mainargs in Scala3? topic at scala-contributors:

    The plan, after discussion in the SIP committee several months ago, is:

    1. In Scala 3.0.0, ship a minimal @main support, that is a strict subset of mainargs and that the committee could build consensus on.
    2. After 3.0.0, revisit and generalize it to support more use cases.

    Perhaps the situation will change one Macro annotations will stabilize. Cf. this post in the same topic:

    I believe the current plan is to build any extension on top of macro annotations, which have an experimental implementation.