14.5. Compiling with scalac and Running with scala

Problem

Though you normally use the Simple Build Tool (SBT) to build Scala applications, you may want to use more basic tools to compile and run small test programs, in the same way you might use javac and java with small Java applications.

Solution

Compile programs with scalac, and run them with scala. For example, given a Scala source code file named Hello.scala:

object Hello extends App {
  println("Hello, world")
}

Compile it from the command line with scalac:

$ scalac Hello.scala

Then run it with scala:

$ scala Hello
Hello, world

Discussion

Compiling and executing classes is basically the same as Java, including concepts like the classpath. For instance, if you have a class named Pizza in a file named Pizza.scala, it may depend on a Topping class:

class Pizza (var toppings: Topping*) {
  override def toString = toppings.toString
}

Assuming that the Topping class is compiled to a file named Topping.class in a subdirectory named classes, compile Pizza.scala like this:

$ scalac -classpath classes Pizza.scala

In a more complicated example, you may have your source code in subdirectories under a src folder, one or more JAR files in a lib directory, and you want to compile your output class files to a classes folder. In this case, your files and directories will look like this:

./classes
./lib/DateUtils.jar
./src/com/alvinalexander/pizza/Main.scala
./src/com/alvinalexander/pizza/Pizza.scala
./src/com/alvinalexander/pizza/Topping.scala

The Main.scala ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.