使用终端从脚本运行 Scala

问题描述 投票:0回答:1

我真的很抱歉,这看起来很基本。我正在使用 Scala 编程,并且必须执行第 4 步:

将其放入名为 hello.scala 的文件中:

@main def m():
        println("Hello world from a script!"

起初我遇到了定义错误的非法开始,因为转向使用 vs code 我得到以下信息:

(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))

我认为这可能是一个新行问题,所以我将所有内容移到一行,例如 @main def m(): println("hello world from script") ,我得到以下内容:

(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))

使用 scalac hello.scala 也不起作用。

scala
1个回答
0
投票

您需要在文件中保留这样的内容:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello, World!")
  }
}

然后保存该文件 say hello.scala

来自终端中的同一文件夹

scalac HelloWorld.scala

然后

scala HelloWorld

© www.soinside.com 2019 - 2024. All rights reserved.