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

990 Views Asked by At

If you follow the steps at the official Scala 3 sites, like Dotty or Scala Lang then it recommends using Coursier to install Scala 3. The problem is that neither or these explain how to run a compiled Scala 3 application after following the steps.

Scala 2:

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

Scala 3:

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

Now how do you run the compiled application with Scala 3?

3

There are 3 best solutions below

8
On BEST ANSWER

Currently there does not seem to be a way to launch a runner for Scala 3 using coursier, see this issue. As a workaround, you can install the binaries from the github release page. Scroll all the way down passed the contribution list to see the .zip file and download and unpack it to some local folder. Then put the unpacked bin directory on your path. After a restart you will get the scala command (and scalac etc) in terminal.

Another workaround is using the java runner directly with a classpath from coursier by this command:

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

Replace myMain with the name of your @main def function. If it is in a package myPack you need to say myPack.myMain (as usual).

0
On

This work-around seems to work for me:

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

This way, you don't even have to compile the source code first.

In case your source depends on third-party libraries, you can specify the dependencies like this:

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

This would be an example where you use the circe library that's compiled with Scala 3. You should be able to specify multiple third-party libraries with the fetch sub-command.

0
On

Finally, it seems that is possible to run scala application like scala 2 version using scala3 in Coursier:

cs install scala3

Then, you can compile it with scala3-compiler and run with scala3:

scala3-compiler Main.scala
scala3 Main.scala