Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.

Scala: Sink or Swim? Part 3

In Scala: Sink or Swim Part 1 and Part 2, we looked at the challenges of Scala complexity from the perspective of a newcomer (especially coming from the Java world). In this post, I’ll give my thoughts on what is so great about Scala in the first place that Java developers should consider using it. A detailed account would take more than one blog post, but I’ll try to give a brief overview with links to relevant reading. Again, this post is mostly meant for Java developers that potentially want to try Scala.

To put it briefly, I think there’s a subset of Scala features that form a relatively simple language that is still quite powerful. I don’t pretend to be an authority on this — and maybe your subset is a bit different from mine (leave comments!). Certainly I’ve left out some useful features here, but I think most of the important ones are covered.

The allure of Scala if you are mostly writing Java now is probably this:

  • More intentional code — i.e. You can get rid of most of the boilerplate stuff
  • DRYer coderepeat yourself less
    • No need to write types in every declaration — they are inferred (mostly)
    • More abstractions — less copy & paste
  • More concise code
    • I think it’s safe to say 2-3 times less lines of code than equivalent Java. Occasionally the difference can be even bigger (or smaller).
  • Immutability is easier
    • Use val (or lazy val) by default instead of var and you might be surprised how seldom you really need mutability
  • Slightly more functional code
    • Scala blends functional and object-oriented programming, so you can start making your code more functional without radically changing your current programming style
  • Functional abstractions over collections
    • forget for-loops — with lambdas, many collection transformations are one-liners
  • New ways to compose things
    • traits enable some compositions that are impossible in Java
  • Pattern matching
    • a huge improvement over if-else chains or switch statements when you don’t want to use polymorphism just to choose between alternatives (which could be most of the time!)
  • Java interoperability
    • something that creates more corner cases and complexity in Scala, but also a blessing as your code can easily interact with existing Java code

Everything above pretty much sums up why I enjoy Scala, so if you’d like to stop reading here, I’ll understand ;-) The reasons for these inevitably vary from person to person, so like I said earlier, please feel free to leave a comment if you think there’s something I should have mentioned. It’s also worth mentioning that Scala code can perform as well as Java code. Some abstractions do have their overhead, though.

Scala features that should make you jump for joy

Above, I wrote down some of the aspects of Scala that I really enjoy, so now let’s look at some of the language features that enable these. The list is not comprehensive, and I will hint at some more features below, but IMHO the main ones are:

  1. Algebraic data types (case classes)
  2. Pattern matching
  3. Traits
  4. Adding methods to existing classes
  5. Syntax
  6. No Primitives
  7. Anonymous and higher-order functions

1. Case classes (a.k.a. algebraic data types)

It’s amazing how easily you can write small classes for holding data in Scala. Even if you don’t use getters and setters in Java, a public data class is still so much code: it usually needs its own file with imports; equals, hashCode, toString implementations and so on. In Scala, if you need a small data class you can often add it to an existing .scala file and just describe the field names and types:

case class Person(firstName: String, lastName: String, age: Int)

Case classes like this are immutable by default, like most data classes should be. equals, hashCode and toString are based on the combination of the fields. The compiler will even add a copy method, which uses current values as default arguments. For example, on my birthday, I could execute this code:

val newMe = me.copy(age = me.age + 1)

Think this is cool? Read more about case classes.

2. Pattern matching

Case classes also interact quite well with pattern matching, which is like a more generalized switch statement. Given our Person class above, we could do some matching on different persons like this:

val aPerson: Person = // find a person
val canDo = aPerson match {
  case Person("Chuck", "Norris", _) =>
    // here we only care about Chuck Norris, and not his age -- Chuck Norris is ageless.
    // Underscore in Scala usually means “wildcard” or “we don’t care about it”
  case Person(_, _, age) if (age >= 18) =>
    // matches only adults who are not Chuck Norris
  case _ =>
    // matches anything else. this is like the default case in Java’s switch
    // if you leave it out you will get a MatchError for a non-matching object

A pattern match, like most control structures in Scala, but unlike those in Java, is also an expression — it can compute a value, which in our case is a Boolean that is true for Chuck Norris and adults, but false for everyone else. Only one of the cases is executed, there is no fall through and there are no break instructions needed.

Pattern matching can also be a good replacement for the Visitor pattern. Read more about pattern matching.

3. Traits

Traits can be used exactly like interfaces in Java, but they can also contain implementation code. If you have a complex type hierarchy, they make it easy to mix several aspects of the implementation from separate traits into concrete classes.

For example, let’s introduce an Ordered trait that defines < and > methods for comparing objects. Implementations must only implement a compareTo method.

trait Ordered[T] {
  def compareTo(other: T): Int // abstract method, returns 0, negative or positive
  def >(other: T) = (this compareTo other) > 0
  def <(other: T) = (this compareTo other) < 0

// we can mix Ordered into an existing class, implement compareTo and get < and > for free!
val ChuckNorris = new Person("Chuck", "Norris", 0) with Ordered[Person] {
  def compareTo(other: Person) = 1 // Chuck Norris is always greater than another person

ChuckNorris > Person("John", "Doe", 22) == true

Of course, this small example isn’t perfect as it only gives us ChuckNorris > person but not person < ChuckNorris. To get both, we’d change the Person class:

case class Person(/*...*/) extends Ordered[Person] {
  def compareTo(other: Person) = /* implement ordering for all persons */

Read more about traits.

4. Adding methods to existing classes

You can, in a way, add methods to existing classes without changing their source code. This is useful for various things, and is achieved by implicitly converting an object of one class to an object of a wrapper class. The methods are defined on the wrapper.

For example, if we wanted to add a method that says whether a person is minor or an adult, we could do this:

class PersonWrapper(p: Person) {
  def minor = p.age < 18
  def adult = !minor
implicit def personWrapper(p: Person) = new PersonWrapper(p)

Person("John", "Smith", 43).adult == true

Personally, I don’t like that “extension methods” are implemented this way, because implicit conversions hold some dangers and are easy to abuse, so you just have to remember to use them responsibly. Read about some hints here.

5. Syntax

You’ve seen some of the syntax in the examples above. It might seem odd at first, with the types coming after names in declarations, but it is quite good once you get used to that change. It’s a nice concise syntax and def compareTo(other: T): Int is more readable than public int compareTo(T other), IMHO. As we saw above, one-liner methods are much nicer than Java equivalents, and infix method calls let us drop the dots and parentheses where we want to (ChuckNorris > person is equivalent to ChuckNorris.>(person)).

Generally, I’d say the syntax lets you do more with less, compared to Java.

6. No Primitives

Scala hides the JVM primitive types from you. Everything is an object, everything can have methods. The compiler will still decide to use primitives where it can, and boxes values where it can’t, but all you see are objects. For example, the Scala library adds a to method to Int, such that 1 to 100 produces a Range you can iterate over:

for (i <- 1 to 100) {
  // do something a 100 times

7. Anonymous and higher-order functions

These barely need a mention. No modern language should exclude anonymous or higher-order functions, and even Java will get them soon. They allow easier parallelization, creating custom control structures and concise code for dealing with collections, among other things.

For example, lets say we often need to do something with all the adults in a collection of Persons. We could create a higher-order method that allows mimicking control structure syntax:

def foreachAdultIn(persons: Iterable[Person])(thunk: Person => Unit) =
  persons filter { p => } foreach { p => thunk(p) }

// now we can write
foreachAdultIn(listOfPersons) { person =>
  // do something with person


Generally speaking, the benefits of Scala have the potential to outweigh the disadvantages, if you know which side of the pool you’re diving in to….you don’t want to hit your head on the bottom after the first jump!

I believe that the main Scala features listed above are already enough to let you write more concise and intentional code than in Java, but getting there is more challenging. For several years, I’ve written all of my hobby code in Scala, and there’s even a bit of Scala code in production at ZT (nothing mission critical, though). But I’ve only occasionally dived into the deeper parts of the Scala swimming pool. They are sometimes fun to explore, but can be scary at first. Even with just the features above and perhaps a bit more, Scala is still my favourite language.

If you or your team of Java developers are considering adopting Scala as an alternative JVM language, let me know about it and maybe I can send you some more pointers – calls are $2.99 per minute ;-) This subset of Scala outlined in this article series might be already enough to make it a compelling choice. You will still enjoy a lot of the power of the language with just these features, and once you are comfortable with that part, you can consider some advanced Scala features and going further in the pure functional direction.

Thanks for your time, and have a productive day!

Want to reach me? Leave your comments below, ping me at or tweet to @t4ffer