How to run simple scripts with Scala?

83 views Asked by At

I have installed Scala (on an air-gapped linux machine from the scala3-3.3.1.tar.gz).

I try to run a simple Scala program without sbt. So I wrote a file hello.scala

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

and then invoked

scala hello.scala 

This works. :-)

But I looked through the Scala 3 website and saw many examples of code without the whole "object wrapping". So I was hoping to write the simpler file script.scala

println("Hello, World")

and run it with scala. But this does not work: Scala returns the error "Illegal start of toplevel definition".

How can I run this? Do I need some command line option for this? Or do I need scala-cli? (I have read scala has become or will become scala-cli.)

I'm confused. What is the best way to run simple Scala scripts on an air-gapped machine.

1

There are 1 answers

2
Jörg W Mittag On BEST ANSWER

Scala 3 does not support script mode. There is an open Scala Improvement Process (SIP) issue about adding back some of the features of the old Scala 2 scala runner.

The way this is going to be implemented is by merging some of the code from Scala CLI, which includes a script runner (among many other things).

The good news is: You don't have to wait for SIP-42 to be implemented, since Scala CLI exists and works right now. Scala CLI scripting has a lot of features that the old script runner didn't have, such as loading additional code or specifying a particular Scala version via the //> using directive.

Note that, if I am not mistaken, the code you showed was never legal Scala code. It was a special sub-variant of Scala, which was only accepted by the script runner integrated into the scala command. This may seem like a technicality, but that is the reason why this is not documented as an incompatibility in the Scala language: it was never part of the Scala language.

If you don't want to use Scala 2 or Scala CLI, Scala 3 has massively improved the syntax for writing main methods, so the example is not nearly as verbose as the example in your question. In Scala 3, your code would look like this:

@main def main = println("Hello, World")

Note that the name of the method can be anything, so if you want to make it shorter:

@main def _ = println("Hello, World")

Main methods have some cool features, for example, you can get command line argument parsing for free, just by defining parameters:

@main def add(a: Int, b: Int) = println(a + b)
scala add 3 4
# 7

scala add 3 four
# Illegal command line: java.lang.NumberFormatException: For input string: "four"

Scala will take the names and types of your parameters and generate command line argument parsing code for you, including error handling and reporting.