Saturday, September 27, 2008

Java vs. Scala - an example from the Google Collections API

As a Java developer, I've heard a lot of hubub, and some would say hype about Scala, so I decided to see what it has to offer. Scala is a multi-paradigm general purpose language, supporting both object-oriented and functional styles. As I learn Scala, I hope to also gain insight into the relative strengths and weaknesses of both languages. This is my first attempt at comparing the two.

Being somewhat familiar with the Google Collections API, I decided to do a simple side-by-side comparison between filtering a collection in Java (using Google collections) versus Scala. Below is the complete Java example, which takes a collection of integers from 1 to 10 and filters them down to only the even numbers:


package com.test;

import java.util.ArrayList;
import java.util.Collection;

import com.google.common.base.Join;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

public class GoogleCollectFilter {

public static void main(String[] args) {
Collection<Integer> ints = new ArrayList<Integer>();
for( int i = 1; i <= 10; i++)
ints.add(new Integer(i));
Collection<Integer> filtered =
Collections2.filter(ints, new Predicate<Integer>() {

@Override
public boolean apply(Integer arg) {
return arg.intValue() % 2 == 0;
}});

System.out.println("(" + Join.join(", ", filtered) + ")" );
}
}


Here now is the equivalent code in Scala:


package com.test

object ScalaFilter {

def main( args : Array[String] ) = {
println((1 to 10).filter((n : Int) => n % 2 == 0))
}

}


If one were to judge purely by verbosity, Scala definitely wins this round. Even with Google's well-designed API, there are still many syntatic hoops that one must go through to do a simple filtering on a collection, due to current limitations in the Java language. Now I'm curious to find an example where the Java code is cleaner. Stay tuned...