Args is Null while extending App [even when runtime args are provided]

Hi,
just learning Scala through docs and came across

in works fine in 2.13 but version 3.1.3 on executing this code
object HelloYou extends App {
if (args.size == 0)
println(“Hello, you”)
else
println("Hello, " + args(0))
}

throws Null pointer Even after providing command line arguments ,

Toplevel definitions have changed in Scala 3. Here’s how you would write this:

@main def helloYou(args: String*) =
    if args.length == 0 then
        println("Hello, you")
    else
        println("Hello, " + args(0))

I was able to reproduce the Null pointer exception you had, on Scala 3.1.2. This might be a compiler bug, I’m not sure (because I reported another similar bug which was fixed). Hopefully someone can confirm.

Word of advice: do not learn Scala from the Docs. Get a book (I recommend “Get Programming with Scala” by Daniela Sfregola) or take a free online Scala course.

3 Likes

App is a terrible idea with a good intention behind it.
It should not be used, it has problems like this, it can lead to initialization order bugs, it doesn’t play well with some other libraries like Spark, etc.

@main and top-level definitions are also terrible ideas with good intentions behind them.
I tried to use them a couple of times and I always found some problem, they should be fixed now but they already lost my trust.

Really just write a regular main method, is not the end of the world.

object Main:
  def main(args: Array[String]): Unit =
    // Your code here.
  end main
end Main

PS: An advice, convert the args to a List

3 Likes

Looks like it’s not a bug, but it was changed in Scala 3, it’s known to fail. I reported and got that response. I think it’s still weird that it compiles but fails to run.

On the docs page it starts with Scala 2, and you have to scroll down to see Scala 3, so that you are using the correct code examples. Confusing.

1 Like