Search code examples
scalascala-2.10scala-3

How to execute a Scala3 script when system has both Scala2 and Scala3 installed?


I want to execute a following script using Scala3:

@main def m() =
  println("Hello, world! I'm a script")

When I type the command, scala hello.scala, I get the following error:

/Users/avirals/dev/learning-scala/hello-world/hello.scala:1: error: not found: type main
@main def m() =
 ^
one error found

I think it is because I have both the versions of Scala installed (2 and 3). I know how to start a REPL for both (as mentioned here) but I am not able to execute a Scala3 script from the command line.

[Update]

I tried scala3-repl hello.scala and it just opens the REPL:

➜  learning-scala git:(main) scala3-repl hello.scala
scala> m()
1 |m()
  |^
  |Not found: m

How do I execute a Scala 3 script from the command line given I have two different versions (2 and 3) of Scala installed?

My OS: MacOS

Update 2

As suggested in this answer, I tried running with amm and it worked for a few scripts. However, the following script failed:

Script:

@main def m(args: String*) =
  var i = 0
  while i < args.length do
    println(args(i))
    i += 1

Error:

➜  learning-scala git:(main) amm printargs.scala
printargs.scala:2:3 expected (If | While | Try | DoWhile | For | Throw | Return | ImplicitLambda | SmallerExprOrLambda)
  var i = 0
  ^

Running the above script in a Scala3-REPL works:

➜  learning-scala git:(main) scala3-repl
scala> @main def m(args: String*) =
     |   var i = 0
     |   while i < args.length do
     |     println(args(i))
     |     i += 1
     |
def m(args: String*): Unit

scala> m("aviral", "srivastava")
aviral
srivastava

Running the same script in a system (MacOS) that has only Scala3 installed works just fine as well.


Solution

  • There exists currently Minimal scripting support #11379. I was able to get it working by manually downloading a release from https://github.com/lampepfl/dotty/releases/download/3.0.0-RC3/scala3-3.0.0-RC3.zip, unzipping, and giving executable permission to launchers

    ./scala3-3.0.0-RC3/bin/scala hello.scala
    Hello, world! I'm a script
    

    With scala3-repl launcher you could at least do

    $ scala3-repl
    scala> :load hello.scala                                                                                                                                                                                      
    def m(): Unit
    
    scala> m()                                                                                                                                                                                                  
    Hello, world! I'm a script