Scala Tutorial (1)

One sign of the success of the Java platform is the profusion of new languages for the Java Virtual Machine (JVM), which appeared during the past few years. Some examples are Jython, Groovy, and JRuby. These languages serve niches in domain specific development where they typically offer better productivity and time-to-market than traditional Java development. One language stands out, however – the Scala language. Unlike many others, Scala is not an adaptation of an existing language to the Java platform, but it has been designed for the JVM from the beginning and it is fully interoperable with the existing Java APIs.

What is more, Scala is a rich statically typed language that provides the ease of use of a scripting language. Scala’s object-oriented features are at least as powerful as those of Java. Scala also offers a full set of functional programming features. It is the felicitous combination of object-oriented and functional properties that makes this language interesting. As of today, Scala already has closures, support for properties, an Erlang-like concurrency API (excellent for multi-core parallel programming) as well as other advanced features that Java will only have in future releases, or possibly never. For this reason, I would like to introduce this language to interested readers in a brief tutorial. Once you get to know Scala, you might agree that it’s a fascinating language. So let’s get started. The obvious starting point is the (in-)famous “Hello World” program, or rather a slightly more involved version of it:

object Hello {
  def main(args: Array[String]) {
    for(val arg: String <- args)
      System.out.println("Hello, " + arg + "!");
  }
}

Any Java programmer should be able to understand what these six lines of code do, despite it being written in a “foreign” language. The program prints a greeting for each of the arguments passed to it. The invocation “scala Hello World” prints the inspiring yet slightly trite line “Hello Word!”. For more fun, you could pass the names of all 190 and odd countries and the program would greet each nation individually. There are some obvious differences to Java. For example, there are no static or void declarations. Another obvious difference is that the program starts with an object definition rather than a class definition. In Scala, the keyword object creates a singleton object, which is akin to a class that contains only static members, except that the Scala object is able to make use of inheritance and polymorphic invocation.

Method definitions start with the keyword def in Scala. The single argument to the main method is args which is of type Array[String], meaning “array of string”. The method contains a for-loop that looks similar to the Java-5 foreach loop construct. It iterates over the elements in the string array args. The expression val arg: String is equivalent to the Java expression final String arg. The keyword val declares an immutable variable, which means that its value cannot be changed after it has been assigned a value. Scala also has mutable variables which are declared with var instead of val. The variable arg is of type String and it takes the value of the iterator variable. It is possible to simplify the program a little:

object Hello { 
  def main(args: Array[String]) {
    for(val arg <- args)
      println ("Hello, " + arg + "!")
  }
}

In this version, the following items have been omitted:

The type declaration : String after arg was eliminated. Although Scala is a statically typed language, which means that every variable has a fixed type, it can infer type declarations automatically. In this case, it infers that the arg variable is of type String because the args variable is of type array of String. This feature is known as type inference and it contributes to making Scala source code more concise by eliminating redundant type declarations. Other examples for type inference are:

val a = "Abacadabra"
val b = 3.141592
val c = Map(1 -> "alpha", 2 -> "beta", 3 -> "gamma")

The types of the variables a, b, c are derived from the literal values. Variable a is a String, b is a Double, and c is a Map that maps Integer values to String values. The above listing also does without the System.out in System.out.println() which results in just println(). Since println() is a frequently used statement, the method context is predefined by Scala. Java programmers may think of this as an automatic static import. Another thing that is absent from the simplified version of the program is the semicolon after the println() call. Semicolons are mostly optional in Scala, except in situations where multiple expressions are stringed together in one line. The code already looks simple, but with Scala we can make it even more concise by replacing the for loop with a foreach() invocation:

object Hello { 
  def main(args: Array[String]) {
    args.foreach(arg => println("Hello" + arg + "!"))
  }
}

The foreach construct iterates over args, creating a String variable arg each time and calls println() on every iteration. The expression with the arrow (an equals sign followed by a greater than sign) this => that can be read “with a given argument this do that”. It is called a function literal in Scala. Granted, in this case it doesn’t save us much typing, but if we wanted to print just the arg variable and if we didn’t refer to it in the expression following the arrow =>, we could just write it as: args.foreach(println), which is the short form for args.foreach(arg => println(arg)).

I hope that this first glance at Scala has whetted your appetite for more. The given examples are fairly unsophisticated. The next section discusses Scala’s types and object hierarchy.