scala 中的 Hello World 有什么问题?

What's wrong with Hello World in scala?

我正在 docs.scala-lang.org 学习 scala。有一个example

object HelloYou extends App {
    if (args.size == 0)
        println("Hello, you")
    else
        println("Hello, " + args(0))
}

scalac编译后我运行scala HelloYou Al得到

java.lang.NullPointerException

其次是

    at java.lang.reflect.Array.getLength(Native Method)
    at scala.collection.ArrayOps$.size$extension(ArrayOps.scala:197)
    at HelloYou$.<clinit>(HelloYou.scala:2)
    at HelloYou.main(HelloYou.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

怎么了?这是我第一次使用 Hello, World 不起作用的语言...

详情

scala -version
Scala code runner version 3.1.1 -- Copyright 2002-2022, LAMP/EPFL

java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)

Scala 3 不再支持访问 command-line 参数:

https://docs.scala-lang.org/scala3/reference/dropped-features/delayed-init.html

App 从来都不是一个好主意,只需编写一个普通的 main 方法即可。

object HelloYou:
  def main(args: Array[String]): Unit =
    args.toList match
      case Nil =>
        println("Hello, you")

      case name :: Nil =>
        println(s"Hello, ${name}")

      case _ =>
        println("Hello, you all")
  end main
end HelloYou