A Brief Introduction to a Few Scala Features

Robert Eccardt

I gave a brief introduction to the Scala programming language at the New York City Java Meetup on October 20, 2008. I followed up with a second part to my presentation at the December 15, 2008 meeting. Notes to that talk are here.

Scala is a hybrid functional/object-oriented language that runs in the JVM. Because it is a statically typed language, its performance is on a level with Java. My intention was to show a few of Scala's features that might be immediately attractive to Java programmers, and how the language is not as strange and off-putting as it might seem at first glance.

I gave the entire presentation using the Eclipse IDE with the Scala plugin. The plugin is available at http://www.scala-lang.org/node/94. It is a complete development environment for Scala applications, including the compiler and the necessary libraries. While it does not have all the advanced features of the Java development environment (such as refactoring), it has many important ones like like code completion, syntax highlighting, hover documentation, etc. It is quite usable and is improving rapidly.

I started off with a small, useless Java program.

package javatest;
import java.util.*;

public class JavaTest {

	static void recurse(int i) {
		if (i % 1000 == 0) {
			System.out.println("hello");
		}
		recurse(i + 1);
	}

	public static void main(String[] args) {
		if (args.length > 0) {
			System.out.println(args[0]);
		}
		List<String> theList = new ArrayList<String>();
		theList.add("one");
		theList.add("two");
		theList.add("three");
		Iterator<String> i = theList.iterator();
		while ( i.hasNext()) {
			System.out.println(i.next());
		}
		recurse(0);
	}
}

Actually, less than useless, since obviously the infinitely recursive method will quickly use up the entire stack and throw an exception:

Exception in thread "main" java.lang.StackOverflowError
	at javatest.JavaTest.recurse(JavaTest.java:10)

Next is a very literal translation of the Java program into Scala. It is extremely awkward Scala code, but it illustrates the similarities of using the two languages, and it shows how Java libraries are directly usable from Scala.

package scalatest;
import java.util._;

object ScalaTest {
  
  def recurse(i: Int): Unit = {
    if (i % 1000 == 0) {
      System.out.println("hello");
    }
    recurse(i + 1);
  }

  def main(args: Array[String]): Unit = {
    if (args.length > 0) {
      System.out.println(args(0));
    }
    var theList: List[String] = new ArrayList[String]();
    theList.add("one");
    theList.add("two");