28 December 2008

Hello World Scala


Why I Am Learning Scala

Multi-core processors are on the ascendancy. The programs you write will normally run in just one of the cores. To take advantage of the additional cores, you will need to write concurrent code. You can do that in Java, but it's a challenge. There is the ever-present possibility of deadlock and race conditions sneaking past your tests.

Functional languages (such as Scala) have an advantage over non-functional languages (such as Java) when writing concurrent programs. A key advantage of functional languages is that they facilitate immutable object state. The fields of an immutable object cannot change underneath your feet and lead to hairy unpredictable behaviour. For instance, Java String objects are immutable. While my program is accessing a String object, I can rely on it remaining the same size and containing the same chars. If I take a substring of my String object, the substring returned is a different immutable String instance and the original String remains unscathed.

Scala
is a well-designed hybrid language which allows both Java-like imperative programming, and functional programming as with Haskell and Erlang. That means I don't have to jump straight into the functional deep end of the swimming pool. I can dip my toes into the water at the shallow end with Scala imperative programming while getting up to speed with functional programming.

Multi-core processors are not going to go away. Even if tomorrow there is a materials break-through and individual cores escape their current physical limits, a concurrent functional program will still have a huge performance advantage on multi-core processors built with the faster cores.

I cannot ignore the trend to multi-core processors. With each increase in the number of cores in a processor -- 2, 4, 8, 16, 32 -- the speed of a single-core process will stagnate at its current level. In fact, with the increased overhead of multi-core processors the usable performance of the individual cores may actually go down.

I decided on Scala for several reasons such as type safety, type inference, performance, closures, and access to all Java's class libraries.

My First Simple Scala main() Program
object HelloScala {
def main(args: Array[String]): Unit = println("Hello Scala!")
}

  1. Save the above three lines of code to a Scala source code file:

  2. HelloScala.scala

  3. Compile with the Scala compiler:

  4. scalac HelloScala.scala

  5. Run by invoking the Scala virtual machine:

  6. scala HelloScala
    Hello Scala!

It's Java Equivalent


class HelloJava {
public static void main(String args[]) {
System.out.println("Hello Java!");
}
}


  1. Save the above five lines of code to:
  2. HelloJava.java

  3. Compile with the Java compiler:

    javac HelloJava.java

  4. Run by invoking the Java virtual machine:
    java HelloJava
    Hello Java!

Further Reading

Followers