Skip to content

@main annotation may conflict with method called main #10137

Closed
@propensive

Description

@propensive

It is reasonably likely that at least some users would choose to name a program's main method, annotated with the @main annotation, as literally main, like so:

@main def main(): Unit = println("Hello, World!")

Unfortunately, compiling such an example twice, with,

dotc hello.scala
dotc hello.scala

will yield one successful compilation and then,

-- [E007] Type Mismatch Error: hello.scala:1:0 ---------------------------------
1 |@main def main(): Unit = println("Hello World")
  |^^^^^
  |Found:    main
  |Required: scala.annotation.Annotation
1 error found

This occurs because the compiled class called main shadows the Annotation class main. But the effect on the user is that they receive a surprising and misleading error message, not least because "it worked the first time, and failed the second time, with nothing apparently changing in between". This could be a very bad user experience at the first try.

An earlier proposal used a program keyword instead of @main, which could have avoided this. Or alternatively an annotation with a different name could be used.

A less satisfactory, but more actionable solution (given how close we are to release), might be to provide a special-case for the @main annotation to print a more meaningful error message to avoid beginners getting confused.

(My own preference would be to introduce a new soft keyword, such as program or main.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions