Compiled Scala applications

Compiled Scala applications

So far, we have written our Scala programs as Scala scripts. Every time you run a Scala script, it is compiled again and then executed. For larger programs, it is better to run them as Scala applications. Scala applications can consist of many source files that can be compiled individually (so you only have to compile the source file that you have changed). A compiled Scala application starts much faster than a Scala script.

Different from a script, a Scala application cannot contain any global variables or functions. All data must be inside objects, all computation inside methods of these objects.

A Scala application can consist of several sources files that define a number of classes and singleton objects. At least one of these singleton objects must define a method main(args:Array[String]) returning Unit. A simple example would be this file (numbers.scala):

object NumberGame {
  var secret = 0
  var guess = -1
  def answerGuess() {
    if (guess == secret)
      println("You got it")
    else if (guess > secret)
      println("Too big")
    else if (guess < secret)
      println("Too small")
  def main(args: Array[String]) {
    secret = (math.random * 100).toInt
    while (guess != secret) {
      print("Guess my number> ")
      guess = readInt()
We can compile this file by saying:
scalac numbers.scala
After compilation—if there were no error messages—some new class files have been created in the current directory, in this case NumberGame.class and NumberGame$.class.

To run the application, say

scala NumberGame
Note that to run a Scala application, you have to provide the name of a compiled object, not a filename. In our case we want to call the main method inside the NumberGame object, so we need to provide the object name NumberGame.

You will notice that a Scala application starts faster than a script. However, the scalac compiler is really slow, because it needs to load a lot of libraries. When you work on your program and you have to compile often, it works much better to use the compiler demon. This is a version of the compiler that keeps itself running in the background, so that it can start much faster. You call it like this (fsc is for fast Scala compiler):

fsc numbers.scala

As an example of a larger compiled application, have a look at the application version of the blackjack game (blackjack-app.scala).