January 03, 2009
Scala for C# programmers, part 1a: mixins and traits, behind the scenes
I wrote yesterday about how Scala's equivalent to interfaces, traits, could include implementation. Given that you can use DLLs built in Scala from C#, this naturally prompts the idea of using Scala traits to get maximal interfaces with minimal implementation in C#:
1. Define trait in Scala and compile into DLL.
2. Reference DLL from C# project.
3. Create C# class which implements the trait.
4. Implement only the abstract members.
5. Get the implemented members for free.
6. Take over the world!
Don't take out the home loan on that extinct volcano just yet, though. Like all plans to take over the world, this one is just a little optimistic.
In Scala, a trait is a type, but at the CLR level, it compiles to two types: an interface representing the trait, and a class containing any implementation. The class is required because a CLR interface can't contain implementation. (Scala could emit the trait as an abstract class, but then a class wouldn't be able to extend more than one trait because of the CLR's single inheritance limitation.) The Enumerable example, therefore, if it were written in C#, would actually look like this (slightly simplified):
public interface Enumerable
public class Enumerable$class
public static int count(Enumerable $this)
/* implementation */
So if you were to create a C# class that implemented Enumerable, your class would have to implement the count() method itself, even though the trait included a default count() implementation when it was defined in Scala.
The Scala compiler, on the other hand, knows to look for the trait implementation class, and sees that it provides an implementation for count(). It therefore automatically adds a count() method to any class that extends Enumerable. The compiler-supplied method body just calls the count() method of Enumerable$class. That is, the mixing in of the trait implementation is a Scala-specific language feature, performed at compile time by Scala and not visible to the .NET type system.
This shouldn't come as any surprise to anyone, but it is a nice illustration of the way that languages can add features over and above what is built into the CLR and specified in the CTS, but that such features will not be mappable into other CLR languages.
TrackBack URL for this entry:
Listed below are links to weblogs that reference Scala for C# programmers, part 1a: mixins and traits, behind the scenes: