You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用终端运行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注解的方法定义语法不符合规范:

  1. 方法声明def m(): 后缺少返回类型(该场景下应为Unit),且未用=连接方法体,Scala会判定这是一个未实现的方法声明,而顶层不允许这类未实现成员。
  2. 合并后的写法错误地将表达式直接放在冒号后,冒号后应指定返回类型,而非方法体。

正确写法

以下两种写法均可正常编译运行:

写法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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:01:14