The past couple of years we’ve seen a blooming of new languages that run on top of JVM. This is not news to anyone. But, moving towards one of those languages is not an easy task, you will need something really strong to motivate you to do it.
After just a few weeks playing with Scala, I think I finally have a new favorit language to code. Ruby and Groovy are great, but they are dynamic type languages (I’m not going into a philosophical discussion here on which approach is right) but to me, static typed languages make code easier to read, and that’s something I’m interested in.
So why Scala? Well one point is that you write less code, another is that you benefit from Functional behavior and finally you get the extras (Traits, Actors)
This first part I’m just gonna show the less code part ok? Later I’ll show interesting stuff like Traits, Actors, and Functional Programming.
1. Dynamic Maps
Have you ever had to create a List
1 2 3 4 5 6 7 8 9 10 11 12 | public List<Map<String, Object>> createList(){ List<Map<String,Object>> entries = new ArrayList<Map<String,Object>>(); Map<String, Object> e1 = new HashMap<String, Object>(); e1.put("name","john"); e1.put("age",35); Map<String, Object> e2 = new HashMap<String, Object>(); e1.put("name","mary"); e1.put("age",32); entries.add(e1); entries.add(e2); return entries; } |
Now let’s compare with scala version:
1 | val entries = List(Map("name"->"joe","age"->35),Map("name"->"joe","age"->32)) |
Wow, just one liner? Yep! And it’s gonna be like this many many times
2. Avoid creation of instance variables
Well lets have a look at the following java code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Shape { private int height; private int width; public Shape(int w, int h) { this.width = w; this.height = h; } public void setWidth(int w) { this.width = w; } public void setHeight(int h) { this.height = h; } public int getWidth() { return width; } public int getHeight() { return height; } } |
This whole variable assignment is just boilerplate code, you really don’t need them on Scala:
1 2 | class Shape(val width:Int, val height:Int){ } |
Again? Just one line? Yep, you’ve been doing boilerplate code for a long time right? We just saved 25 lines here
On Scala, if you prefix you constructor arguments with either val (immutable) or var (mutable) keywords, a field instance is already created for you.
3. Default values for method arguments
I miss this
I hate having to do this:
1 2 3 4 5 6 7 8 | public void draw(Integer sides, Float radius){ if(sides == null || sides == 0){ sides = 3; } if(radius == null || radius == 0){ radius = 1.0f; } } |
Where I could be doing :
1 2 | def draw(side:Int=3, radius:Float=1.0f) = { } |
I really find this default value handy. And we just saved another 6 LOC
4. Forcing constraints
Sometimes you need to enforce a specific domain constraint on your objects. Let’s say you don’t wan’t your Shape class to have width and values that are less equal than zero right. So:
1 2 3 4 5 6 7 | public Shape(int w, int h) { if(w <= 0 || h <=0){ throw new IllegalArgumentException(); } this.width = w; this.height = h; } |
In Scala we can actually force this on our class as required constraints:
1 | require(width>0 && height>0) |
Now, free your mind and read both snippets of code again, doesn’t the Scala version makes way more sense now?
5. Type inference
Although Scala is a static typed language, it can reduce part of you boiler code as it can infer some types for you.
Integer x = 1; List<Integer> intList = new ArrayList<Integer>(); intList.add(1); intList.add(2); intList.add(3);
val x = 1 val intList = List(1,2,3)
The Scala code you don’t need to define the type, as the compiler will infer for you, also note how simpler it is to declare lists. Thanks God Java 7 has something called the diamond operator which will allow you (not me as I’ll quit writing java code by there) write things like this: List
6. Named parameters
Another nice thing from Scala is support the named parameters. Remember our draw method?
shape.draw(5,2.0f) shape.draw(radius=1.0f,sides=4)
Scala will allow you to pass parameters on their order, or any order you want as long as you specify it’s names.
7. No more checked Exceptions
Debatable, but I hate them. I hate having to close a resource, and having to check for exception on my finally clause. Hate it to death. This unchecked approach is one of the things I like most on the design of Spring Data Access exceptions, they are all unchecked.
def draw(sides:Int=3, radius:Float=1.0f) = { if(sides > 99) throw new UnsupportedOperationException } shape.draw(15,2.0f) //No catching here :D
8. Methods everywhere, parenthesis nowhere
The first good thing is: Scala is a OO language, not like Java. Java is something that can be OO, but you can also write static everywhere and find your self in a C procedural world (I’ve been there, worked with great guys from C, that started writing java code, and not a line of OO).
So you can actually call:
1.until(10)
which will create a Range of integers from 1 to 10. This is nice, but what looks cool, and make your code so readable that even you mom can read is:
1 until 10
So, when you do 1+1 you are actually doing: 1.+(1)
9. Embrace Functional Programming
This is a more advanced topic, and I’m still getting used to it, but a simple way to see this is: Everything returns something
. I mean, every language execution must return something or Unit (kinda void). This is such a powerful feature once you get used to it, your if-else statements can return a value, your loops, your try-catch. This will reduce your code a lot
val max = if(x>y) x else y val nums = 0 until 9 val odds = for { i <- nums if i%2!=0 }yield i println(odds)
One could argue on the max example being possible using ternary operator (which I use a lot, and now I understand why, I had a deep need for Functional Programming). But the capacity of yielding values as your for loop gets evaluated is really powerful. Combine this with the inline if conditions, and you have a very powerful filter without having to rely on external Predicate classes
10. goodbye semicolons
Well, you probably noticed this already. No semicolons needed here.
Conclusion
Well there are so many reasons on why you should move to Scala, that was actually hard coming up with only 10 that were simple to explain. Next time I’ll dig into traits and actors, and maybe get more people to join the Scala Army.
Happy Coding

