Scala is my next choice

 Jul, 12 - 2009   31 comments   Scala

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:

Where we define the Type T to be a sub type of Animal. It can be more flexible even:

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