MattHicks.com

Programming on the Edge

Loops in Scala

Published by Matt Hicks under , , , on Thursday, October 01, 2009
Lately I've been learning the ins and outs of the Scala language and I have to say, having programmed in Java for the past several years, that Scala is scratching where I itch. It is a lot to grasp and mind opening, but all-in-all I see Scala as what Java could have evolved to if they would have just been willing to ditch some backwards compatibility and fix some stuff rather than just adding more and more work-arounds.

Anyway, that's not the point of this post. I wanted to post some cool loop examples I've been playing with in Scala.

In Java we have the standard incrementing for-loop:
for (int i = 0; i < 10; i++) {
...
}

In Scala we have something similar, but I believe more elegant:
for (i <- 0 until 10) {
...
}

However, with Java 1.5 we got the enhanced for-loop when we don't care about indexes:
for (String s : listOfStrings) {
...
}

In Scala we do something similar, but with a more consistent syntax:
for (s <- listOfStrings) {
...
}

Or, we can go a step further with Scala since it's a functional language we can get rid of the for loop entirely and use a friendly method available to us called "foreach" and pass each entry to another method:
listOfStrings.foreach(doSomething);

def doSomething(s:String):Unit = {
...
}

To me this is of significant appeal because we don't end up with a bunch of embedded for-loop blocks in our methods we focus more on modular functionality to deal with the results of the iteration instead.