How to run scala file from command line?

11.1k Views Asked by At

Does scala support scala run xxx.scala? The go language supports running like

go my.go

and python supports

python my.py

but it seems

scala xxx.scala

is only a syntax check, no output or running behavior is observed. So is there a way to run a scala file directly?

4

There are 4 best solutions below

1
Tausif Sayyad On

Before running scala source code, you need to compile scala code by using scalac filename.scala command. To execute compiled scala file you need to type following command: scala filename

0
Scalway On

I definitely recommend ammoninte for such cases. It is separated tool but has much more features and works well.

more on http://ammonite.io/

1
Mario Galic On

scala runner's target can be explicitly specified via -howtorun

If the runner does not correctly guess how to run the target:

 -howtorun    what to run <script|object|jar|guess> (default: guess)

for example, say we have an fat jar, then we could run it with

scala -howtorun:jar myapp.jar

By default scala runner tries to guess and run the named target either as

  • a compiled class with a main method
  • a jar file with a Main-Class manifest header
  • a Scala source file to compile and run

For example, given the following Hello.scala source file

// source file Hello.scala
object Hello {
  def main(args: Array[String]): Unit = {
    println("Hello World!")
  }
}

then executing scala Hello.scala should output Hello World! by the third bullet-point above.

Also consider Your First Lines of Scala.

0
som-snytt On

It seems pretty easy. But you have to use println to print something.

➜  ~ cat hello.scala
println("hello, world")
➜  ~ scala hello.scala
hello, world
➜  ~ scala -Vprint:parser hello.scala
[[syntax trees at end of                    parser]] // hello.scala
package <empty> {
  object Main extends scala.AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    def main(args: Array[String]): scala.Unit = {
      final class $anon extends scala.AnyRef {
        def <init>() = {
          super.<init>();
          ()
        };
        println("hello, world")
      };
      new $anon()
    }
  }
}

hello, world
➜  ~ 

or there are a few ways to feed lines to the REPL, which prints results for you.

➜  ~ cat calc.scala
2 + 2
➜  ~ scala < calc.scala
Welcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 11.0.3).
Type in expressions for evaluation. Or try :help.

scala> 2 + 2
res0: Int = 4

scala> :quit
➜  ~ 

See also -i, -I, -e, and the :load and :paste commands.

As shown in the other answer, it will also look for a Java-style main method in an object. That's how you'd normally compile a program entry point.