Scala is my next choice

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:

  • Scala Does Rock.
  • I do believe this language should be taught in CS colleges and institutes.

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:

  • This article is not to compare languages, it’s to address why you should learn Scala.
  • Scala has 2 implementations right now, one that runs on the JVM, and one that runs on the CLR. However the JVM one is more mature, and I believe it’s better to stick to the advice of David Pollack(Lift framework creator) to use F# if you want to work with .Net framework. However I will stick to JVM implementation in this article.
  • I’m a Rubiest, and I still like Ruby cause it’s the best dynamic language ever, but I like Scala also because it has some features that are so powerful for other work domains.

Now, let’s dive into the some reasons that’s makes Scala my next language of choice:

A hyper language

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:

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:

Notice how the previous code snippet is more readable and more concise than the Java equivalent.

Efficient

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.

Scalable

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:

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.

Object Oriented

  • Everything in Scala is an object(except for the objects’ methods), so there is no need to differentiate between primitive or reference types, this is called: Uniform Object Model. But as I mentioned earlier during the optimization process, value type objects are converted to Java primitive types, so don’t be worried about the performance.
    There are also singleton objects to group class methods inside them.
  • All operations are method calls, + - * ! / all are methods, so there no need for operator overloading.
  • A great fine-grained access control, where you can control access for certain methods for certain packages also.
  • Scala has 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.

Functional

A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:

Functions are first-class values

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.

Pure functions

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.

Better concurrency model

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.

Statically typed

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:

Code written in statically typed languages is more robust

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.

Code written in statically typed languages is so strict and verbose

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:

But you can do this also:

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:

<

pre lang=”Scala”>
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:

<

pre lang=”Scala”>
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.

Pattern matching

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:

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.

Easy DSLs

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.

Interoperable with Java code

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.

Educational language

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..

Team

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.

Roots

Scala was inspired by many languages:

  • Most of the syntax is coming from Java and C#.
  • Other elements where adopted from Java such as: basic types, class libraries, and its execution model.
  • Its uniform object model was pioneered by Smalltalk.
  • Its idea of universal nesting is also present in Algol, Simula, and, more recently in Beta and gbeta.
  • Its uniform access principle for method invocation and field selection comes from Eiffel.
  • Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members.
  • Many higher-order functions in Scala’s standard library are also present in ML or Haskell.
  • Scala’s implicit parameters were motivated by Haskell’s type classes. Scala’s actor-based concurrency library was heavily inspired by Erlang.
  • The specific idea of treating an infix operator as a function and permitting a function literal (or block) as a parameter, which enables libraries to define control structures can be traced back to Iswim and Smalltalk.

Experts’ Opinions

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:


At the end of this point I like to sum things up:
I like Scala because it’s efficient, educational, has better concurrency model, and very good for writing DSLs.
I also want to share another secret with you:
I’m planning to write a book on Scala language, I have an idea at mind and would like to coauthor with any guy from the Scala camp, please ping me if you have the same attention as mine.


Real World Examples

Resources

31 Replies to “Scala is my next choice”

  1. 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.

  2. 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.

  3. 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:

    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.

  4. @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.

  5. @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.

  6. 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.

  7. 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!

  8. @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:

  9. 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.

  10. 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.

  11. @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

  12. @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

  13. 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.

  14. Pingback: Twitted by liet
  15. 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 ).

  16. @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.

  17. Hiya, I’m really glad I have found this info. Today bloggers publish only about gossips and web and this is really annoying. A good website with exciting content, that is what I need. Thanks for keeping this site, I’ll be visiting it. Do you do newsletters? Can not find it.

Leave a Reply

Your email address will not be published. Required fields are marked *