I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter’s Ruby vs Scala debate. Now and after few months of work with this language I really want to share you two ideas that are no secrets anymore:
I’m going to justify my opinion during this article, just before doing so I have few notes I feel like I have to address:
F# if you want to work with .Net framework. However I will stick to JVM implementation in this article.Now, let’s dive into the some reasons that’s makes Scala my next language of choice:
Scala is a hyper language that enables you to code in imperative and functional paradigms, so you can code with the normal imperative style just like we do in C, Java, PHP and many other languages, or you can code in a functional style like we do in Lisp for example, or you can mix both, just like we do in Ruby or Groovy.
However, one distinct to Ruby and Groovy when talking about the functional paradigm, is that Scala almost supports all known features of functional languages, like Pattern matching, Lazy initialization, Partial Functions, Immutability, etc…
That’s said, it’s important to address the fact that the power of Scala comes from it’s support for the functional paradigm, which makes the language a high-level one. A high-level language makes you focus on ‘what’ to do rather than ‘how’ to do.
Look at this Java example:
int[] x = {1,2,3,4,5,6}; ArrayList<Integer> res = new ArrayList<Integer>(); for (int v : x) { if (v % 2 == 1) res.add(new Integer(v)); }
If you focus on the previous example, you will notice that the ‘what’ part of what I want to do (Filtering odd values) comes on the 4th line, and the other lines are just the ‘how’ part of it(result var initialization and a loop), thus if I want to write another filter for even numbers, It will take me another 5 lines to do the same, while in a high-level languages like Scala, you will need to express the ‘what’ part only:
val x = Array(1,2,3,4,5,6) val res = x filter ( _ % 2 == 1 ) //filtering odd numbers val res2 = x filter ( _ % 2 == 0 ) //filtering even numbers
Notice how the previous code snippet is more readable and more concise than the Java equivalent.
Scala is an efficient language, actually due to the latest benchmarks Scala is almost as fast as Java. The JVM implementation of Scala compiles down to bytecode, but during so, the code passes through optimization phaze. An optimization example is the tail recursion optimization, to help you stick to the functional paradigm without sacrificing the performance. Another example is the optimization done to convert Scala value type objects to Java primitive types.
The name of Scala language comes form the word ‘Scalable’, meaning that this language grows with the demand of its users. So basically you can add new type and control structures. For example I want to add a simple ‘loop’ control structure:
// simple implementation def loop(range: Range)(op: Int=> Unit) { range foreach (op) } loop(1 to 5){println} // 1 2 3 4 5 loop(1 to 5){x => if (x % 2 == 0) println(x)} // 2 4
A more comprehensive example is the Actor lib, which is added as an extension to the language, we will talk about it later on.
However what makes Scala Scalable is two related things: being pure object oriented and being functional.
+ - * ! / all are methods, so there no need for operator overloading. traits, similar to mixins in Ruby, which are like interfaces in Java but have some of their methods implemented, thus you can have rich wrappers and interfaces out of the box.A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:
Which means that you can pass them as values and return them as values as well. This leads to concise readable code just like the filtering examples mentioned above.
Scala encourages pure functions that have no side effects, meaning: when you have the same input, you will always have the same output. This will result in safer and easier to test code.
But how does Scala encourages pure functions? By immutability: Favoring fixed references(like final in java or constants in other languages) and having immutable data structures that once created can’t be modified.
Immutability is the safe guard to have pure functions, but it’s not the only way. You still can write safe code without immutability. That’s why Scala doesn’t force immutability but it encourages it. Eventually you will find that many data structures in Scala have 2 implementations, one is mutable and the other is immutable, immutable data structures are imported by default.
Some concerns regarding performance might arise when talking about immutability, and while these concerns are valid in this context, it turned out that things are somehow reversed when it comes to Scala. Immutable data structures tend to be more efficient than mutable ones. One reason for that is the existence of a robust garbage collector like the one of JVM. You can find more information about the efficiency of immutable data structures in Scala in this blog post.
When it comes to threading, Scala supports the traditional shared data model. However and after long experiments with this model, many people found it to be so hard to to implement and test concurrent code written using this model. You will always have to consider deadlocks and race conditions. Thus Scala suggests another concurrency model called Actors, where an actor sends and receives asynchronous messages in it’s inbox instead of sharing data. This is called: shared nothing model. Once you stop thinking about shared data, you relief yourself from the headache of thinking of code synchronization and deadlocks problems.
Together the immutability nature of the sent messages and the serial processing of messages in the actor, leads to easier concurrency support.
There are 2 articles(1,2) on the IBM developerWorks website that cover Scala concurrency deeply. Please refer back to them to have a better idea about this topic.
Before I move to the next point I need to mention the fact that some people consider the use of Actors as an evolutionary progress in programming languages. As Java came and relieved programmers from the headache of pointers and memory management, Scala came to relief programmers from thinking all the time of code synchronization and the problems raised by shared data model.
When i wanted to cover this point, I found myself trying to weigh both the pros and cons of a statically typed language. Actually there is an endless debate regarding this topic but I tried to sum things up to two points that I found most people talking about:
It’s true that with the existence of TDD most of the talk about dynamically typed systems and robust code starts to lose its value, but one fact still exists: in dynamically typed languages you write more tests to check types, while in statically typed ones, you leave things out for the compiler. Also some people argue that with a statically typed language you have a better self documenting code.
Fans(just like me) of dynamically typed languages argue that they can produce more dynamic code structures through duck typing. Also they complain about the verbosity introduced with statically typed languages.
You can read more about static versus dynamic typing here.
Scala as a statically typed language will gain the first point, but how about the second one?
Scala has a flexible type system, and may be the best of it’s type. So in many cases this system will be able to infer the type in case you didn’t specify it.
For example you can do this:
val list: List[String] = List("one", "two", "three") //list: List[String] = List(one, two, three) val s: String = "Hello World!" //s: java.lang.String = hello world!
But you can do this also:
val list = List("one", "two", "three") //list: List[String] = List(one, two, three) val s = "Hello World!" //s: java.lang.String = hello world!
Well, that’s cool as it solves the verbosity problem somehow. But what about things like duck typing?
Again: Scala’s type system has some flexibility that enables you to do things like:
def eat[T <: Animal](a: T) // whatever
Where we define the Type T to be a sub type of Animal. It can be more flexible even:
def eat[T <: {def eat(): Unit}](a: T) // whatever
Where we define the type T to be a type that has the method eat.
Actually Scala’s type system is so rich, you can find more about that here.
I have to admit that I hesitated a lot to write about this feature, actually I didn’t want to cover functional features of Scala, but after I read this specific post regarding switch use with objects, I thought it’s good to talk about this feature.
So basically and taken from this post :
So what does pattern matching do? It lets you match a value against several cases, sort of like a switch statement in Java. But instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects.
And the following example:
x match { case Address(Name(first, last), street, city, state, zip) => println(last + ", " + zip) case _ => println("not an address") // the default case }
In the first case, the pattern Name(first, last) is nested inside the pattern Address(…). The last value, which was passed to the Name constructor, is “extracted” and therefore usable in the expression to the right of the arrow.
Then
The purpose of pattern matching
So why do you need pattern matching? We all have complicated data. If we adhere to a strict object-oriented style, then we don’t want to look inside these trees of data. Instead, we want to call methods, and let the methods do the right thing. If we have the ability to do that, we don’t need pattern matching so much, because the methods do what we need. But there are many situations where the objects don’t have the methods we need, and we can’t (or don’t want to) add new methods to the objects.
So, Pattern matching is considered a valid way of extensibility, and it offers a great solution to this problem apart from the verbosity that comes with Visitor design pattern.
Anyway, it’s highly recommended that you read the “Two directions of extensibility” in the previous mentioned article.
Scala is very good for coding DSLs. Actually Scala is suitable for both Internal and external DSLs. You can find in this article a little comparison of features between Ruby and Scala for writing internal DSLs. Check this cool post on internal DSLs using Scala: Boolean Algebra Internal DSL in Scala (aka fun with Unicode names ).
Also when it comes to External DSLs, Scala should be your first choice, and the reason behind that is the parser combinator lib, that makes writing compilers for new languages is really cool. You’d better follow this cool post to get a better idea about what Scala can do.
The JVM implementation of Scala have seamless integration with Java platform, actually many Scala types compiles down to Java types, so you can use Java libs safely. Also you can make some work between JVM languages like JRuby, Groovy, Clojure and others.
Here is a good post with examples.
I had 2 habits that I kept practicing during the learning curve of Scala :
Both of these two habits made me gain more knowledge and increased the quality of my code through some good practices like: writing pure methods that has no side effect and focusing on the ‘what’ part of my code, leaving the ‘how’ one to language abstractions..
Scala was designed by Martin Odersky the man running the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology in Lausanne (EPFL). Odersky was approached by Sun to write the Java 1.1 compiler, he was the lead developer of javac from Java 1.1 through Java 1.4. Also he is the guy behind Java Generics.
Scala is being maintained by Odersky and his team at EPFL. However there are other talented folks who helped shaping Scala over years, you can check the full list here.
Scala was inspired by many languages:
This article is a very good one showing some for experts’ opinions regarding Scala language. Actually it has some surprises like James Strachan’s(creator of Groovy language) statement:
I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy
Also I have found these interviews to be very useful:
Fadil | July 12th, 2009 at 7:03 am #
Great article
Yes indeed that Scala is a good language, but one thing i would like to say is that if you want to build decent Web applications with Scala & Lift then you’re stuck. I know that Lift is very young and flexible in some means but its very very hard to use with lots of things that you have to do to get a small little works. On the other hand Grails is the best Web framework I’ve ever worked with.
Anyway am not against the Lift framework, but i can say they they have lots and lots to do to reach a level of high productivity gains and an easy way of doing things like with Grails.
reboltutorial | July 12th, 2009 at 7:09 am #
Hi, that’s just what I was looking for: an introduction to scala for an absolute newbie like me. I know another great functional language that is Rebol ( see reboltutorial.com ) so I think I will love Scala also though I find the syntax not as simple than Rebol.
I will learn Scala | July 12th, 2009 at 11:34 am #
Indeed I will read these 2 books:
Programming in Scala: A Comprehensive Step-by-step Guide
Beginning Scala
And use Rebol to help me learn Scala see why here:
http://reboltutorial.com/scala/i-will-learn-scala-programming-with-the-help-of-rebol/
popurls.com // popular today | July 12th, 2009 at 2:40 pm #
popurls.com // popular today…
story has entered the popular today section on popurls.com…
Scala is my next choice – Khaled alHabache’s official blog « The other side of the firewall | July 12th, 2009 at 2:53 pm #
[...] July 12, 2009 at 5:53 pm · Filed under Java, Programming [From Scala is my next choice - Khaled alHabache’s official blog] [...]
Jeff | July 12th, 2009 at 11:20 pm #
While Scala does have some interesting features, and surely is a better option than Java or C#, it seems bloated to me though, with all these type declarations, overrides, and object-oriented whiz-bang. Actually, after reading your very nice article I was intrigued so I started reading a bit more about Scala, including some code examples. Here’s one from the scala website:
So that’s printing out a map of colors to codes. Pretty straight forward, but it still seems like lots of cruft to me.
Have you taken a look at Clojure? I think it provides every one of the benefits you mention above for Scala, but in a much more consistent and I would argue powerful way. At a minimum I would watch one of Rich Hickey’s presentations at http://clojure.blip.tv/ to get a feel for what it’s all about. Anyway, here is the above example in Clojure:
(def colors {"red" 0xFF0000 "turquoise" 0x00FFFF "black" 0xFFFFFF "orange" 0xFF8040 "brown" 0x804000}) (defn main [] (doseq [[color code] colors] (println color "has code:" code)))Pretty concise, and you don’t give anything up. It’s great to have an ecosystem of new languages that can explore ideas in different contexts, so I’m glad Scala is pushing the boundaries. I’ve enjoyed Clojure a lot though, so people interested in a new language on top of the JVM should check it out.
khelll | July 13th, 2009 at 12:55 am #
@fadli, Yes Lift is not as mature as Rails or Grails.
On the other side when it comes to Rails and Grails, I would Recommend Grails for Java and J2EE developers, otherwise I would recommend Rails.
khelll | July 13th, 2009 at 12:55 am #
@reboltutorial, Good Luck
khelll | July 13th, 2009 at 12:56 am #
@Jeff, Do you think that with Clojure Syntax you can do DSLs?
Also, the Scala snippet above is a handling the case where the user input is not available in the map.
28 fresh design-links « Adrian Zyzik’s Weblog | July 13th, 2009 at 2:32 am #
[...] 2 CE :: Silvergames.com 12SEO iPhone 68 Is Free The Future Of Enterprise Software? Yes And No. Scala is my next choice – Khaled alHabaches official blog Collapse in illegal sharing and boom in streaming brings music to e… JS-Kit ECHO Social Media [...]
ScalaVsClojure | July 13th, 2009 at 3:48 am #
Clojure and Scala are quite diffrent. You can do a lot stuff you do in Clojure in Scala, but also vice versa:
http://www.nabble.com/something-like-Clojure%27s-%22doto%22–td24400202.html
a “LISP” Programming languages has a very small Core this has also advantages and disadvanteages.
For the main-stream java programmer. It is already hard to get used to scala. Clojure involves a lot more think diffrent concepts. And most programmes don’t like that, even though they don’t tend to say it directly.
links for 2009-07-13 « pabloidz | July 13th, 2009 at 4:02 am #
[...] Scala is my next choice Khaled alHabache’s official blog (tags: scala) TagsCategoriasmiudezas Uncategorized [...]
jimmyjj | July 13th, 2009 at 6:35 am #
Good article. Felt that way myself a way back – but please consider skipping scala and moving directly on to erlang. You get a lot of the functional programming, but with a concurrency model that is da bomb (dead simple primitives + real time code updates + real time debugging, etc..). Cheers!
daghf | July 13th, 2009 at 8:30 am #
@Jeff,
I don’t think your comparison is quite fair, as the Scala snippet you posted
does not just print out the map. The Scala program takes parameters from the command line, looks these up in the color map, and prints out the corresponding color code.
A Scala equivalent of the Clojure code you posted would be something like this:
Tinou | July 13th, 2009 at 1:07 pm #
think we need to be careful about the powers of scala. afaik, there’s some elementary tail call optimization in scala, but only the most basic ones. the jvm just doesn’t support tco and there’s a lot of challenges getting tco properly in. while the actor model may be a better concurrency model, it too is vulnerable to deadlocks. scala is cool, but lets not make it out to solve every problem out there.
Rida Al Barazi | July 14th, 2009 at 12:49 am #
Very interesting read, you encouraged me to read more about Scala now
very well put.
I will also learn clojure and fan | July 14th, 2009 at 6:59 am #
Clojure seems also interesting. Some othe also mentionned to me that Fan was less permissive than Scala, so I will study the three at the same time
Geir | July 14th, 2009 at 9:02 am #
Good post. I mostly agree with you, even if I don’t think Scala has enough going for it (yet) to actually become a viable competitor to Java. Personally, I am rooting for qi4j.
On the other hand: You say that message-driven systems are free from deadlocks. I am afraid that is not true, at least not for the level of reader you are addressing. It is easy to (mis)architect your application so you get two consumers waiting on output from each other with message-based systems too. You also have to contend with race conditions.
It all seems worth it to get rid of synchronization, though.
khelll | July 15th, 2009 at 3:23 am #
@Tinou, you are right regarding TCO, hopefully things will be better with Java 7-8, however new things are out for Scala 2.8 to aid the programmer checking if his code is optimized or not, check this blog post
khelll | July 15th, 2009 at 3:25 am #
@Tinou and Geir, You are right, message driven systems are not totally safe of deadlocks, but helps you to get rid of them to a big deal. I should have mentioned that.
Thanks
Henri | July 15th, 2009 at 5:10 am #
Just like garbage collection didn’t completely solve memory leaks. You still have to be aware of some of the dangers, just not ALL of them.
Nice post Khaled. I do have a concern about the ’scalability’ of Scala. This is very powerful, but therein also lies a big risk. Many (inexperienced?) programmers may be tempted to start adding their own loop syntax, their own operators, etc., often to resemble the syntax of another language. This will render the code totally unreadable to anybody else (remember the templates in C++).
Would you say that Scala is not intended for the ‘lower level’ programmer? Of course, this all may go away if you do proper pair programming.
Benjamin A. Shelton | Blog » Blog Archive » Links of the Week: July 15th | July 15th, 2009 at 6:04 pm #
[...] alHabache has an insightful write-up on Scala. I’ve been eyeing the language off for a couple of months now, but I think [...]
Sri | July 17th, 2009 at 10:51 pm #
Scala is a hybrid Object-Oriented/Functional Programming language on the JVM. When I heard that Twitter was using Scala, I was curious and started collecting all the sites and articles to learn scala programming. If you are interested check the link below for the big list I have gathered (more than 200 sites) for learning scala programming.
http://markthispage.blogspot.com/2009/06/more-than-100-sites-to-study-scala.html
Twitted by bubbl_scala | July 18th, 2009 at 6:44 pm #
[...] This post was Twitted by bubbl_scala [...]
Twitted by liet | July 18th, 2009 at 8:25 pm #
[...] This post was Twitted by liet [...]
geo | September 7th, 2009 at 11:19 pm #
The only thing I have agains Scala is the syntax. Look at an example that makes use of Scala’s generics, or some “not-so-basic” functional programming and tell me how much of it can you understand ( if you haven’t coded in Scala before ).
Dan Sickles | October 4th, 2009 at 7:59 pm #
@geo, Look at an example that makes use of Java’s generics (if you haven’t coded in Java before) Even scarier…and I learned Java generics before learning Scala. I like Scala’s generic syntax better…maybe because I was abused by c++
I agree that the flexible syntax can be abused but Scala’s creators take the position that it’s up to you where to draw that line.
Is Scala the new Java? - The Daily Kebab | October 28th, 2009 at 6:12 am #
[...] jallen on Oct.28, 2009, under Uncategorized According to Khaled alHabache Scala is his next choice, is this really better than [...]