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


Malvolio says:
Agree with everything except your remark about the checked exception on close() — that isn’t a Scala advantage so much as a bug in the Java IO library. Why give me any exception, let alone a checked one, on close()? What do you expect me to do?
If Scala’s close() doesn’t throw any exception at all, that’s a step forward.
Tuesday, June 21, 2011, 13:51WhyIsEverythingOnOneLineSoGreat says:
ArrayList<Map> entries = new ArrayList() {{ add(new HashMap() {{ put(“name”, “john”); put(“age”, 35); }}); add(new HashMap() {{ put(“name”, “mary”); put(“age”, 32); }}); }};
What do I win?
Tuesday, June 21, 2011, 14:43JG says:
Pretty sure everything that you’ve mentioned above can also be said for Groovy.
Tuesday, June 21, 2011, 15:25hasen says:
as someone said on HN: when you move away from Java, everything looks good.
Tuesday, June 21, 2011, 15:32Rory says:
In example 2 – shouldn’t the code be:
class Shape(var width : Int,var height : Int)
rather than val as the java example has mutable fields.
I’m also a big fan of the fact that case classes generate sensible toString,equals and hashcode for free as well
case class Shape(var width : Int,var height : Int)
Tuesday, June 21, 2011, 18:02Blake Matheny says:
What are your thoughts on doing 0 until 9 filter { i => i%2 != 0 } instead of a for loop at all? Just getting started with Scala as well so I’m not sure what the preferred way would be.
Tuesday, June 21, 2011, 19:25Manish Pandit says:
You can shorten 9 to just :
val odds = for (i <- 0 to 10 if i%2!=0) yield i; println(odds)
That said, thanks for the great post. Its awesome to see scala gaining momentum in the mainstream.
Tuesday, June 21, 2011, 23:06Martin Mauch says:
In 2. Avoid creation of instance variables the Java versions has setters for the fields, so the Scala version should use vars instead of vals.
Nice article, I like the clean look of your blog
Wednesday, June 22, 2011, 5:48autoreverse says:
Should the first Java example be:
e2.put(“name”,”mary”);
e2.put(“age”,32);
(not e1)? Had me puzzling for a moment.
Wednesday, June 22, 2011, 6:51Michael E. Cotterell says:
You should probably mention in section 2 (Avoid creation of instance variables) that you can recreate the java getters and setters with the @BeanProperty annotation:
import scala.reflect.BeanProperty
class Shape(@BeanProperty var width: Int, @BeanProperty var height: Int)
Also, note how the brackets are missing in the class definition. In this case, you don’t need them unless you’re doing other stuff in the class.
Wednesday, June 22, 2011, 14:41fkpwolf says:
some features are similar with Ruby. but you missed the Actor
Wednesday, June 22, 2011, 23:49Java know how says:
Below is a more concise version of the Java code. With the new Java 7, this is going to become even shorter… like this is the most important thing in the world.
I looked at Scala and I always find it way to complex for any enterprise development. It gives you enough rope not only to hang yourself, but a small African village. The academic roots of Scala creators (people that never had to develop and MAINTAIN enterprise code) are obvious.
Another problem with Scala fans is that .. they do not know all features of Java and make
pretty poor comparisons. Claiming that java does not have default parameters or named parameters means that you never bothered to read “Effective Java” or learn about the Builder pattern.
————————————————————
public List<Map> createList(){
return new ArrayList<Map>({
add(new HashMap({
put(“name”,”john”);
put(“age”,35);
}));
add(new HashMap({
put(“age”,32);
put(“name”,”mary”);
}));
});
Thursday, June 23, 2011, 18:22}
Argan Wang says:
in section “9. Embrace Functional Programming”
Thursday, June 23, 2011, 22:17odds can be rewriten by :
val odds = nums.filter(_%2!=0)
Alexander Bokov says:
It is unclear what Scala strives for. On the one hand it is built by Ph.D. students whose primary interest is to get their thesis done. On the other hand there is Typesafe with Akka. Akka is really nice, since it is designed and developed by smart people having years of programming experience. Maybe they do not write papers, but they are capable of designing APIs and providing stable implementations.
I want to address some very interesting points (hopefully not only to me). XML support provided by the Scala language could be a nice thing, if it would be done right. But as is, it not only unnecessarily complicates the syntax, but having many gotchas and design mistakes, as pointed out here http://www.codecommit.com/blog/scala/working-with-scalas-xml-support, hurts the image of Scala. Now, XML is getting quite unpopular and JSON is simply a better data exchange format for some kinds of applications. Do we need to screw up the Scala syntax a second time and integrate JSON syntax? Of course no, there are some nice libraries, for example Lift’s JSON library, which proves that Scala has a really flexible syntax. I claim that the same could/should be done for XML. It does not make sense to mix in a completelly different syntax into a general purpose language. I can only speculate about the reason, but ironically, it could sound like this: “Since Scala is a unifier by its philosophy, we must have XML literals. It does not make sense not to have them in Scala”. XML is not the only example. Scala actors in the standard library are not the best thing too, see for example http://scala-programming-language.1934581.n4.nabble.com/Removing-Scala-Actors-from-Lift-td1978541i20.html. The version 2.9.0 escaped the laboratory before it was carefully tested. One can find really funny discussions addressing this issue. The package scala.io should not be included in the standard library or its content should be declared private – it would help avoid some stupid discussions (somebody had an idea to compare scala.io with Ruby’s IO libraries. Obviously scala.io was not meant to be something what its name states). A question like “what’s the right way to use scala.io.Source?” (asked here: http://stackoverflow.com/questions/4458864/whats-the-right-way-to-use-scala-io-source) is simply answered – there is the only one right way: do not use it. There are more examples, I encourage you to look around.
Thus on the surface it is really nice, but if you look deeper, you will see a lot of ugliness. I play with Scala since about 3 years. Sad I have to say “play”. The language seems not to follow any clear strategy, it is driven by experiments, which cause headache in practice. Some of these “experimental features” get fixed, but some of them cannot be fixed easily.
The compiler is damn slow, you will hard time to explain to your manager, why the software deployment process takes 30 instead of 10 minutes. How can one be productive if IDEs need to be restarted multiple times a day? Emacs is not an option, some people including me, are not willing to give up their tools. Stability, trustworthiness and prudent design of a language and its ecosystem – these are my Gods and of many people, who are not paid for experiments.
I hope people behind Scala will draw some conclusions and reconsider their strategy.
Saturday, June 25, 2011, 20:21Jed Wesley-Smith says:
minor point but your odds impl can be simplified:
val odds = (1 to 9) filter (_ % 2 == 1)
also, performance-wise you should really use bitwise AND though for mod any power of two:
val odds = (1 to 9) filter (i => (i & 1) == 1)
unfortunately the i param is necessary as & is overloaded for the AnyVal types.
Sunday, June 26, 2011, 2:54admin says:
Well, still pretty messy for a simple thing such as map creation.
I really don’t agree on you statement against scala. I’ve been developing java apps for over 9 years. Been through many frameworks and programming models, and since java 1.3 we have not seen the language evolve. And that’s my point here.
Java as a language lacks the features that new languages offers to boost your productivity. I’m not complaining, I know it has to maintain backward compatibility, but it does not mean that we need to keep using it.
So far, scala has been (in my personal opinion of course) the best choice out there. It combines the nice things about FP, keeps your code cleaner, and at the same time it’s static typed
And the best part is that you can mix and match with java. For instance, right now I’m working in a REST project with SpringMVC on the front end, but scala as services, and we are finding the results pretty impressive (in terms of making it easier to maintainr for instance).
And if I have to use a pattern to have default parameters so I’m sorry I do not have default parameters. Of course I can achieve most anything using patterns and proxies and fancy code, but this is the whole point I’m trying to avoid here. One could achieve Trait capabilities with proxies, or use anonymous classes for closures, but that is just filling your code with more unnecessary boilerplate.
Tuesday, June 28, 2011, 6:30admin says:
Indeed, ruby is also a notable language. Not yet, just waiting for part 3
Tuesday, June 28, 2011, 6:31admin says:
Thanks. gotta update that.
I was hoping to have enough material for part 3 to add a section about integration with Java, and add the annotation there, but thanks for bringing it up
Tuesday, June 28, 2011, 6:32admin says:
Thanks Manish, I’m still trying it and getting used, thanks for the best version of my example
Tuesday, June 28, 2011, 6:32admin says:
Yeah, for this part most of it. I hope that the next parts I’ll be able to bring something extra.
I love groovy, I still find grails unbeatable when it comes to productivity. But I’m kinda moved away from Groovy after some bad performance tests I’ve seen and tried. I know we have groovy++ but, not trying to get in a holy war here, I really enjoy static typing languages, and I find Scala the champion out there when it comes to this point.
Regards
Tuesday, June 28, 2011, 6:35