For the first set of articles introducing the Scala language, I will largely be paraphrasing and summarising an excellent series of articles, Scala for Java Refugees, by Daniel Spiewak and Scala and XML by Michael Galpin.
Getting hold of Scala
To start with, you will need a Java runtime environment, version 1.4 or later.
Next, you should download the latest Scala distribution for your platform from here. At the time of writing, the 2.7.1-final version of Scala was a 13Mb download.
Unpack the Scala archive, set the SCALA_HOME environment variable to the place you unpack it, and add $SCALA_HOME/bin (Unix) or %SCALA_HOME%/bin (Windows) to your PATH.
First of all, we must obey the tradition of learning a new language by writing the canonical “Hello, World” program. Here goes:
Put this code into a file named hello.scala, and then run the following commands:
> scalac hello.scala
> scala HelloWorld
So, why is Scala better than Java?
You can write Java-like code in Scala, but it takes less typing and can be much more readable. For example:
Some things to note from the Scala example code above:
- The default constructor is a part of the class declaration.
- You don’t have to state that the member “size” is an Int – the type is inferred from pSize, which is already declared to be Int. Likewise for “name”, which is inferred to be a String.
- Semicolons at the ends of lines are optional.
- Properties do not need get/set methods (see “size”).
- If you need it, you can implement get/set logic by defining a property and overriding the “=” method (see “name”) – no change is needed to code calling your class.
- Access to existing Java classes is transparent – the IllegalArgumentException is exactly the same one used by Java.
Just to show how Java-compatible Scala is, here is the class file generated by the Scala code above, decompiled back to Java (using the cavaj tool):
As you can see in the name_$eq() method’s null test, the Java produced by Scala is actually better quality than the original Java!
If you really want to have Java-style getX() and setX() methods generated as well, all you need to do is add a BeanProperty annotation to each property definition:
This adds the following code to the class file:
I hope that gives you a small taste for what Scala can bring to the NetWeaver Java platform. Next time, I’ll dig a little deeper into some of the things that are unique to Scala, such as pattern-matching and the ability to use XML directly in the language.