Friday, November 23, 2007

I just discovered the "Scala" language, thanks to an excellent article "Java EE meets Web 2.0" ( on IBM's developerWorks. Scala is very close to Java and generates class files that run on the JVM. I am a user and a fan of Groovy, but I am interested in Scala for its Actors library: Actors are "tasks" that can send and receive messages synchronously or asynchronously. There is a short tutorial at by Philipp Haller, the author of the library.

The Scala documentation says that Scala objects can call Java objects and vice-versa. I wanted to write a code snippet to see how a Java application can create and call Scala objects. It's very basic but it works!

A Java class "Zoo" with the "main" method creates a Scala object "Dog" and calls its method "talk".

Running the Zoo main on Windows:

C:\ScalaTest>java Zoo
Woof, woof!

Here it is the code for the 2 files and Dog.scala:

class Zoo {
public static void main(String[] args)

Dog dog = new Dog();;
} // main
} // class Zoo


class Dog
val sound = "Woof, woof!"
def talk() = println(sound)
} // class Dog

How to build it on Windows:

Compile the Scala file first:
C:\ScalaTest>scalac Dog.scala

Then compile the main app, Java will find the Dog.class

Run it:

C:\ScalaTest>java Zoo
Woof, woof!

"Zoo" is printed by the Java Zoo class
"Woof, woof" is printed by the Scala "Dog" class.

That's it!

Preliminary steps to install Java and Scala:
  • install a JDK (download it from
  • add the path to your java \bin folder (something like C:\jdk1.5.0_09\bin) to your PATH environment variable.
  • check that the Java compiler is accessible by opening a cmd window an typing "javac" and return. A list of options will be displayed, starting like this: "Usage: javac ...".
  • add the Java libraries to the "classpath" environment variable, something like this: "classpath=.;C:\jdk1.5.0_09\jre\lib\rt.jar;C:\jdk1.5.0_09\lib\tools.jar;"
  • install Scala (download it from
  • add the Scala bin folder to your PATH environment variable. Should look like this: "...;C:\scala-2.6.0-final\bin;"
  • add the Scala libraries to the "classpath" environment variable. Should look like this with the Java libraries: "classpath=.;C:\jdk1.5.0_09\jre\lib\rt.jar;C:\jdk1.5.0_09\lib\tools.jar;C:\scala-2.6.0-final\lib\scala-library.jar;"
  • check that the Scala compiler is accessible from a cmd window: "C:\ScalaTest>scalac" will display a list of options: "Usage: scalac ..."

That should do it. If not, check for Java installation issues and for the Scala ones.

I am off to try some Actors code in Scala.

No comments: