Scala for the Impatient

I spent a few hours this weekend digging through the first 4 chapters of Scala for the Impatient from Typesafe. I had heard a lot about Scala from various folks around the functional programming and Java communities, usually in the same sorts of conversations as Haskell and F#. I decided it was time to go take a browse through the language and see what it's about.

On first glance, Scala is in that same family of "Post-Java" languages as Groovy, Python, Ruby, etc. with lots of syntactic sugar that makes it fun to work in. It doesn't require semi-colons. It doesn't require parenthesis on function calls in certain cases. It's statically typed, but the compiler guesses your types for you in most cases, so you don't have to worry about it unless you're doing something tricky. This is refreshing coming from Java, C#, or even ColdFusion where the compiler requires a pretty rigid syntax before it lets your code pass.

Another area where Scala really shines is in processing collections. Arrays, Lists, and Hash Maps are all very nice to write for. This is again something that is shared with Groovy, Python, Ruby, and the rest of the "Post Java" languages. For example, in Java if you want to copy only the odd numbers in an array into a second array, you have to do something along these lines:

int[] a = {1,2,3,4,5,6,7,8};
int[] b = new int[4]; // How do I know there are 4?  I just do...
int counter = 0;
for( int i : a ) {
  if( i % 2 == 0 ) { 
    b[counter++] = i;

Or something like that. In Scala, the whole thing becomes a lot shorter, more concise and readable (once you know the Scala syntax of course).

val a = Array(1,2,3,4,5,6,7,8)
val b = for( i <- a if (i%2=1) ) yield i

Or maybe

val a = Array(1,2,3,4,5,6,7,8)
val b = a.filter(i=>i%2=1)

I'm a little worried that Scala suffers from the problem that Perl sometimes has: You can do the same thing so many different ways that it's possible to "outsmart yourself" and end up with code that's effectively write-only. It takes more effort to mentally parse what's going on in this code than it does to write it.

Of course, the ability to manipulate collections in interesting ways is great, but the Google Guava library, as well as the Apache commons address that pretty well too. It's not clear (from the first few chapters) that Scala's collection processing capabilities are ultimately that compelling, but there are several chapters left to go.