如何使用 Coursier 在命令行中 运行 Scala 3 应用程序

How to run Scala 3 applications in the command line with Coursier

如果您按照官方 Scala 3 站点上的步骤操作,例如 Dotty or Scala Lang,那么它建议使用 Coursier 安装 Scala 3。问题是这些都没有解释如何 运行 一个已编译的按照步骤操作后的 Scala 3 应用程序。

斯卡拉 2:

> cs install scala
> scalac HelloScala2.scala
> scala HelloScala2
Hello, Scala 2!

斯卡拉 3:

> cs install scala3-compiler
> scala3-compiler HelloScala3.scala

现在如何 运行 使用 Scala 3 编译应用程序?

目前似乎没有办法使用 coursier 为 Scala 3 启动运行程序,请参阅 this issue. As a workaround, you can install the binaries from the github release page。一直向下滚动通过贡献列表以查看 .zip 文件并将其下载并解压缩到某个本地文件夹。然后将解压后的 bin 目录放在你的路径上。重新启动后,您将在终端中获得 scala 命令(和 scalac 等)。

另一种解决方法是通过以下命令直接使用 java runner 和来自 coursier 的类路径:

java -cp $(cs fetch -p org.scala-lang:scala3-library_3:3.0.0):. myMain

myMain 替换为您的 @main def 函数的名称。如果它在包裹 myPack 中,您需要说 myPack.myMain(像往常一样)。

这个解决方法似乎对我有用:

cs launch scala3-repl:3+ -M dotty.tools.MainGenericRunner -- YourScala3File.scala

这样,您甚至不必先编译源代码。

如果您的源依赖于第三方库,您可以像这样指定依赖项:

cs launch scala3-repl:3+ -M dotty.tools.MainGenericRunner -- -classpath \
    $(cs fetch --classpath io.circe:circe-generic_3:0.14.1):. \
    YourScala3File.scala

这将是您使用用 Scala 3 编译的 circe 库的示例。您应该能够使用 fetch 子命令指定多个第三方库。

最后,似乎可以 运行 在 Coursier 中使用 scala3 等 scala 2 版本的 scala 应用程序:

cs install scala3

然后,你可以用scala3-compiler和运行用scala3编译它:

scala3-compiler Main.scala
scala3 Main.scala