使用终端运行Scala脚本时遭遇编译错误求助
解决Scala 3 @main方法编译错误问题
问题重现
按照《Programming in Scala》步骤编写hello.scala,初始代码:
@main def m(): println("Hello world from a script!")
编译时出现报错:
(base) *dir* scala % scala hello.scala Compiling project (Scala 3.5.1, JVM (21)) [error] ./hello.scala:2:12 [error] end of toplevel definition expected but '(' found [error] println("hello world from script") [error] ^ [error] ./hello.scala:1:11 [error] Declaration of method m not allowed here: only classes can have declared but undefined members [error] @main def m(): [error] ^ Error compiling project (Scala 3.5.1, JVM (21))
合并代码为一行后仍报错:
(base) *dir* scala % scala hello.scala Compiling project (Scala 3.5.1, JVM (21)) [error] ./hello.scala:1:23 [error] end of toplevel definition expected but '(' found [error] @main def m(): println("hello world from script") [error] ^ [error] ./hello.scala:1:11 [error] Declaration of method m not allowed here: only classes can have declared but undefined members [error] @main def m(): println("hello world from script") [error] ^ Error compiling project (Scala 3.5.1, JVM (21))
错误原因
Scala 3中@main注解的方法定义语法不符合规范:
- 方法声明
def m():后缺少返回类型(该场景下应为Unit),且未用=连接方法体,Scala会判定这是一个未实现的方法声明,而顶层不允许这类未实现成员。 - 合并后的写法错误地将表达式直接放在冒号后,冒号后应指定返回类型,而非方法体。
正确写法
以下两种写法均可正常编译运行:
写法1:显式指定返回类型,用花括号包裹方法体
@main def m(): Unit = { println("Hello world from a script!") }
写法2:省略返回类型(Scala自动推断为Unit),直接连接表达式
@main def m() = println("Hello world from a script!")
验证
将正确代码写入hello.scala后,执行命令:
scala hello.scala
即可正常输出Hello world from a script!。
内容的提问来源于stack exchange,提问作者clueless
相关产品推荐
相关产品推荐

