First Steps With Scala 3
Published: 2021-07-17So Scala 3 was released on May 13, 2021. I wanted to start writing some Scala 3 code but it turns out that Gradle doesn't support Scala 3 yet. I might be tempted to use sbt but for now let's do it like it's 1999...
First, let's download the Scala 3 release to our computer. I know that the Scala website says to use Coursier, but come on, it's not that serious. Just curl the tarball to your computer:
$ cd $HOME
$ mkdir -p Zoo/scala3
$ cd Zoo/scala3
$ curl -LO https://github.com/lampepfl/dotty/releases/download/3.0.0/scala3-3.0.0.tar.gz
$ tar -xvzf scala3-3.0.0.tar.gz
Let's put the scalac
binary on our shell's path:
$ cd scala3-3.0.0/bin
$ export PATH="$(pwd):$PATH"
And verify:
$ cd $HOME
$ which scalac
/home/cosmin/Zoo/scala3/scala3-3.0.0/bin/scalac
$ scalac
Usage: scalac <options> <source files>
...
Great! We can run the Scala compiler. Now what?
The Getting Started With Scala 3 again recommends Coursier (I didn't realize it became the "Scala Installer"), but I know I have my JVM installed, so I just want to get writing ...
Let's create another directory:
$ cd $HOME
$ mkdir -p Zoo/scala3/first-scala3-doodle
$ cd Zoo/scala3/first-scala3-doodle
$ vi Main.scala
Let's take the Main.scala
from the Scala 3 Hello World template and write the code in our Main.scala
:
@main def hello: Unit =
println("Hello world!")
println(msg)
def msg = "I was compiled by Scala 3. :)"
A few things have changed from Scala 2, but it looks pretty familiar still. Of course we have to show off the optional braces and the @main annotation. Save it and get back to the console.
Now let's compile it:
$ scalac Main.scala
$ ls
hello.class hello.tasty 'Main$package$.class' 'Main$package.class' 'Main$package.tasty' Main.scala
Alright, we have compiled our first Scala 3 code! Now let's run it.
$ export SCALA3_HOME="$HOME/Zoo/scala3/scala3-3.0.0"
$ java -cp "$SCALA3_HOME/lib/scala3-library_3-3.0.0.jar:$SCALA3_HOME/lib/scala-library-2.13.5.jar:." hello
Hello world!
I was compiled by Scala 3. :)
Yay! It worked! Note that we now need both the Scala 3 and the Scala 2.13.x libraries on the classpath.
From here on it should be easy to tinker around with the code. Locally you also have access to the built-in Scala REPL:
$ scala
scala> println("It works!")
It works!
In the long run you should probably use a build tool that supports Scala 3 (seems like right now it's Mill, Maven, and sbt).
Or try it out online with Scastie.