Sometime ago I came from Madrid to Rotterdam to join Lunatech’s international workforce. Apart from introducing me to Dutch summers (rain), this also gave me an opportunity to learn a new programming language: Scala.

Since I finished university I’ve been working with Java and I really liked it, but Scala was something entirely new to me. In this post I’ll give my first view on Scala from a Java perspective.

Many people say that Scala is like Java but without semicolons, but I disagree. It’s true that Scala doesn’t need semicolons, and that may save developers some time, but it’s just a minor feature. One of the things that really caught my eye when I started, is related to style: unlike Java developers, Scala developers like to put everything on the same line. Let’s consider the next piece of Java code:

public Foo someMethod(Foo foo, Bar bar) {
Foo firstResult = foo.doSomething();
Bar secondResult = bar.doOtherThing();
Foo finalResult = doLastThing(firstResult, secondResult);
return finalResult;
}

We could have compressed that into something smaller, but usually Java developers love verbose stuff: to define variables with long names so everything looks clear and people can understand what’s happening on the code. On the other hand, a Scala developer would do something like this:

def someMethod(foo: Foo, bar : Bar) : Foo = doLastThing(foo.doSomething, bar.doOtherThing)

Basically, the main thing that me, as a Java developer, saw when reading Scala code is “try to put everything on the same line”, and that makes things a bit difficult to understand at the beginning. But in the end your Scala code ends being very small and powerful.

Another thing that stands out are Collections. When you are learning Collections in Java, most of the times you start with arrays (Foo[]) and later you probably move to ArrayList. Then, iterating over your Collection of choice is made with for/while loops most of the time, with some logic inside the curly brackets. But Scala’s Collection library is more powerful and easy to use than the one you have available in Java.

Recent versions of Java have implemented new libraries with similar tools as in Scala, but they have been developed a few years ago, and most of the times they require weird implementations of the Stream class. Scala, on its side, was created with this kind of tools in mind, so they are far more accessible and easy to understand.

In Scala, the map method (and the rest of their friends: flatMap, flatten, head, tail, filter, etc) makes iterating through Collections so easy and safe, that you even try to use it as much as you possibly can. You don’t have to worry about IndexOutOfBoundsException anymore. When you can transform this:

for (int i = 0; i < intList.size(); i++) {
if (intList.get(i) % 2 == 0)
intList.set(i, intList.get(i) + 1)
}

Into this:

intList.map(x => if (x % 2 == 0) x + 1 else x)