If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Monday, March 29, 2010

Scala traits

Let us first step back and look into Java interfaces. A Java interface typically is defined as a thin interface, meaning it only describes the minimal required methods to get the work done. The main reason is that the more methods an interface defines, the heavier the burden becomes for the implementer of that interface.

The real issue though is that in Java an interface itself can't provide any concrete implementation.

Let me explain this by a concrete example.



You should agree that isLast() could easily be derived using hasNext().

In java we cannot put actual implementation code in the interface all concrete classes implementing this interface need to do so or extend from a abstract class which implements isLast().

Scala traits are comparable to java interfaces. They describe methods which an object should implement but they can provide concrete implementations themselves.


So in scala the best practice is to write only a few ABSTRACT methods and enrich the interface with a lot of concrete methods implemented based upon these abstract methods.

Like a Java interface a Scala trait can also have NO constructor parameters. In Java a class can implement multiple interfaces using the 'implements' keyword. An interface itself can extend 1 other interfaces using the 'extends' keyword.

In Scala you can extend a Trait using the 'extends' keyword. This would mean you also implicitly inherit from the trait's superclass. But you could also mix-in the trait using the 'with' keyword.

A nice example of implementing a very thin abstract interface (toXML and fromXML) extended with concrete rich interface methods is shown below.






The output on my console:


Another big advantage is that traits are stackable through linearization used by the scala compiler.

... TODO: workout some examples

No comments:

Post a Comment