In Part 2 of this series we’re going to move into some of the object-oriented aspects of Scala.  For a primer on what Scala is, and a quick primer on syntax, check out part 1.

Let’s start with the built-in object structure

Like C# and Java, Scala has a built-in object hierarchy, and a standard library full of goodies.  Unlike Java and C#, Scala tackled the issue of reference types and value types head-on, so while the root type in the Scala type system is the Any type, there are two descendants of Any that come into play before any other type. The two are: AnyRef, and AnyVal. As you might guess AnyRef is the base type for all reference types (including types made available from Java), and AnyVal is the base type for all value types. This is a little bit like the class and struct type constraints in C#, only you can use these as variables. They can also be used to limit type parameters, but Scala Generics are going to have to get their own post.

There is one other interesting class that makes Scala unique from C# and Java (and maybe even other OO languages…I don’t think Ruby does this….pretty sure python doesn’t either….Smalltalk probably had it, but then Smalltalk had everything).  There is a class called Nothing, which is a Subclass of every class. I’ll give that a second to sink in.  Ok, got that? There is also another class called Null that is similar in that it is a Subclass of every reference type.  Here is a diagram of the Scala class hierarchy to make things a little clearer.

With this information fresh in our minds, lets take a look at actually putting together some Object-Oriented code.

The Trinity….Classes, Objects, and Traits

This was actually one of the first areas that made me go “Wow” in Scala land. Being on the JVM, you would expect it to use Java’s notion of classes and interfaces. But, interestingly, while it is built to support interoperability with Java directly, Scala starts asserting itself early on in the following way: In Scala you have three basic building blocks for OO, the Class, the Object, and the Trait. Taking these in order of most like what C# devs are used to up to the least, we’ll start with the Class. Classes in Scala are basically like C# classes…only with one significant difference: Scala classes do not have Statics. As a matter of fact there is no way to make a Class static in Scala. That’s where Object comes in. Object is basically a singleton, which you reference using static-like syntax (so Name.Method). You can create something which looks like statics on classes by using a Companion Object, that is an Object which has the same name as the Class (and is in the same file). Objects have a couple special things going on like the ability to be used as Factories for other classes, and the special apply() and unapply() methods, which allow you to get instances of object, and come into play in nifty ways when we start talking about Pattern Matching. But before we get into that lets talk about the last of the Scala OO Trinity, the Trait. So Traits are really cool….they are effectively Interfaces, only they can contain implementation. I say can, but they don’t have to. So you can use Traits in a way that is similar to the way interfaces are used, or you can add implementation, and they become Mixins. What’s more, you can create a Trait that inherits from a Class, as well as a Class that extends a Trait. You can also create Objects that inherit from classes and extend Traits. You can also attach a Trait to an instance of a class at the time you instantiate the class, which means you can add behavior to a class declaratively at the time you need it. So lets get some code samples going here, just to give an idea of what this all looks like. Lets put together a totally non-realistic example of an Animal class hierarchy:

class Animal

Ok, that was maybe no so helpful (but I will point out that this is valid, code…it compiles people, try it out). Lets move on to some categorization

class Feline extends Animal {
  var _lives:Int = 9

  def creep {
  }
  def scratch {
  }
  def hunt {
  }
  def livesLeft:Int = _lives
}

class Canine extends Animal {
  def howl {
  }
  def hunt {
  }
  def chaseFeline(cat:Feline) {
  }
}

So now we have a little more to work with…not much, but it’s a start. Before we get too far, we have some duplication, so lets do a little refactoring…since both classes have a hunt method, we’re going to pull this out into a Trait:

trait Hunting {
  def hunt {
  }
}

And to actually make use of this, our classes are now:

class Feline extends Animal with Hunting {
  var _lives = 9

  def creep {
  }

  def scratch {
  }
  
  def livesLeft:Int = _lives
}

class Canine extends Animal with Hunting {
  def howl {
  }
  
  def chaseFeline(cat:Feline) {
  }
}

There, isn’t that nice? The Trait is added to the class in this case with the addition of the with keyword (though if there was not a base class, we would need to use the extends. The rule is the first item is extends, and any other traits use with). We could also do this declaratively at instantiation time if we wanted. Like this:

val canine = new Canine() with Hunting
 

Before we finish up (cause I think this is plenty to chew on for a while), I want to talk briefly about visibility and overrides.  By default in Scala, everything is public…as a matter of fact there isn’t a public keyword at all. There are actually some really interesting options for scoping which give you more control than the public,private,protected,internal,protected internal options available in C#, but those will have to wait for a bit. As far as overrides, Scala does not have a virtual keyword. So everything is overridable (sort of). Unlike Java, if you want to override something you have to use the overridekeyword. Lets put together a quick example:

class Animal {
  def sleep {
  }
}

class FruitBat extends Animal {
  override def sleep {
    if(isNighttime)
      super.sleep()
  }
}

Again, contrived, but so are most samples on blogs. Naturally we’ll ignore the fact that isNighttime has no implementation, cause we can, and look at the fact that overriding existing functionality is pretty familiar to the C# dev, except for the call to super rather than base. The interesting thing to note here is that, by default, all methods can be overridden in Scala (using the final keyword on a method def will keep it from being overridden), and you must be explicit when you do it. This actually takes care of the complaints from folks, particularly when discussing testability, about C# requiring the virtual keyword to allow it to be overridden (and since everything is public by default, there is that argument too). It also takes care of complaints people have about the fact you can “accidentally” override methods in Java, since you don’t have an overridekeyword (Some IDEs will look at an @Overrides annotation, but there is nothing checked at compile time for this).

We’ve covered quite a bit, and there are still some things we could talk about, but this takes care of the basics. You can now create Object Oriented code in Scala. In our next installment we’ll dig in to the Scala concept of Generics, which actually makes C# generics look like a sad and feeble attempt at doing something interesting (while still dealing with type erasure in the JVM).

I’m going to take a brief intermission in my Scala series, and show a head-to-head comparison of some code in Scala and C#.  To do this, I’m going to go with the first and second problems from Project Euler.  If your not familiar with the site, it’s a playground full of problems that are absolutely perfect for functional languages (cause they tend to be mathematical functions).  So let’s get started with Question #1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

We’ll start with the C# version:

public class Problem1
{
   public int GetResult()
   {
       return Enumerable.Range(1, 999).Where(i => i % 3 == 0 || i % 5 == 0).Sum();
   }
}

With the magic of Linq this is pretty easy (I’ll show later how Linq is basically a way to do list comprehensions in C#, but that’s for one of the longer posts).  Now, on to the Scala version (which you can paste into your REPL or SimplyScala if you want):

(1 until 1000).filter(r => r % 3 == 0 || r % 5 == 0).reduceLeft(_+_)

Now, comparing these too, they are fairly similar. Creating the initial range of numbers is a little easier in Scala (and using the until “keyword” means we don’t have to use 999 like in C#). Instead of the Where Scala uses the more traditional filter function, and we have to do a little more work and use the reduceLeft function with the special _+_ I talked about before, but overall they are quite similar.

So let’s move on to Question #2. It is:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Seems pretty straight forward.  We want a Fibonacci sequence generator, then we simply need to filter out odd values, and sum the even values that are less than 4 million to get our answer.  Lets start with C#:

public class Problem2
{
    private IEnumerable<int> Fibonacci()
    {
        var tuple = Tuple.Create(0, 1);
        while (true)
        {
            yield return tuple.Item1;
            tuple = Tuple.Create(tuple.Item2, tuple.Item1 + tuple.Item2);
        }
    }

    public int GetResult()
    {
        return Fibonacci().Where(i => i % 2 == 0).TakeWhile(i => i < 4000000).Sum();
    }
}

This one is a little more involved because we have to generate a Fibonacci sequence. I decided to use an iterator and the magical yield keyword to make a never-ending sequence (well, never ending until we end up with an overflow exception that is), but beyond that the solution is very similar to problem #1.

Now for the Scala version:

lazy val fib:Stream[Int] = Stream.cons(0,Stream.cons(1,fib.zip(fib.tail).map(p => p._1 + p._2)))
fib.filter(_ % 2 == 0).takeWhile(_ <= 4000000).reduceLeft(_+_)

Well, isn’t this interesting….The first line is the equivalent of our C# iterator.  It’s creating a lazy stream which is a stream who’s contents are calculated as they are needed (just like our iterator).  The difference here is that Scala doesn’t try to evaluate it all if you just type fib into the REPL..it will give you the first few results and then say “Look, I could go on, but you didn’t tell me how far to go so I’m just going to stop here”, and it spits out a ? to let you know that there could be more. This means that Scala has a deeper understanding that this thing may well never end.  Keeping this in mind we’re actually calculating it’s contents recursively (after hard-coding the 0 and 1 values)) by using the zip function, which will take a list and combine it with another list into a collection of Tuples. For the second list, which gets passed in to the zip function on fib we’re specifying fib.tail which is our list, minus the first element. So if our list starts out looking like List(0,1,...) then fib.tail is List(1,...). That means the initial call to zip creates the tuple (0,1). Now, from there we use the map function (translate this to Select in Linq-ease) to return the sum of the first and second items from out tuple. So now we have just created the third element in our sequence: 1. So the next time round this all happens again, only on the next elements in the two sequences respectively. So the zip function returns a tuple with the second and third element in the sequence: (1,1), and low and behold the 4th element in our sequence is born. This will go on until you stop asking for values, or you get an overflow exception. The entire time the evaluation of what is in the sequence is exactly one element ahead of what is being returned. Kinda mind bending, no? Now for the second line, we once again have an almost one-to-one map to our C# code. We filter out the odd values, take all the values less than 4 million, and then sum up the results.

Hopefully this has been at least a little bit enlightening…I’ll continue on making some more detailed forays into the world of Scala, but I thought an occasional one to one comparison might be help shed some light on some of the places where Scala offers some added elegance to what is possible in C#…as well as those spots where it doesn’t.