Monday, February 15, 2010

Self Annotation vs inheritance

At first glance the "sself annotation" declaration seems similar to extending another class. (For a look at self annotations read the topic: Self Type.) They are completely different but the comparison is understandable since both of them provide access to the functionality of referenced class.

For example both of the following compile:
  1. class Base {
  2.   def magic = "bibbity bobbity boo!!"
  3. }
  4. trait Extender extends Base {
  5.   def myMethod = "I can "+magic
  6. }
  7. trait SelfTyper {
  8.   self : Base => 
  10.   def myMethod = "I can "+magic
  11. }

But the two are completely different. Extender can be mixed in with any class and adds both the "magic" and "myMethod" to the class it is mixed with. SelfType can only be mixed in with a class that extends Base and SelfTyper only adds the method "myMethod" NOT "magic".

Why is the "self annotations" useful? Because it allows several provides a way of declaring dependencies. One can think of the self annotation declaration as the phrase "I am useable with" or "I require a".

The following example demonstrates one possible reason to use self annotations instead of extend.

Note: These examples can be pasted into the REPL but I have shown that here because it would make the examples too long.
  1. import
  2. import java.util.{Properties => JProps}
  3. trait Properties {
  4.   def apply(key:String) : String
  5. }
  6. trait XmlProperties extends Properties {
  7.   import scala.xml._
  9.   def xml(key:String) = Elem(null,key,Null,TopScope, Text(apply(key)))
  10. }
  11. trait JSonProperties extends Properties {
  12.   def json(key:String) : String = "%s : %s".format(key, apply(key))
  13. }
  14. trait StreamProperties {
  15.   self : Properties => 
  17.   protected def source : InputStream
  19.   private val props = new JProps()
  20.   props.load(source)
  22.   def apply(key:String) = props.get(key).asInstanceOf[String]
  23. }
  24. trait MapProperties {
  25.   self : Properties =>
  27.   protected def source : Map[String,String]
  28.   def apply(key:String) = source.apply(key)
  29. }
  30. val sampleMap = Map("1" -> "one""2" -> "two""3" -> "three")
  31. val sampleData = """1=one
  32.                     2=two
  33.                     3=three"""
  34. val sXml = new XmlProperties() with StreamProperties{
  35.               def source = new ByteArrayInputStream(sampleData.getBytes)
  36.            }
  37. val mXml = new XmlProperties() with MapProperties{
  38.               def source = sampleMap
  39.            }
  40. val sJSon = new JSonProperties() with StreamProperties{
  41.               def source = new ByteArrayInputStream(sampleData.getBytes)
  42.             }
  43. val mJSon = new JSonProperties() with MapProperties{
  44.               def source = sampleMap
  45.             }
  46. sXml.xml("1")
  47. mXml.xml("2")
  48. sJSon.json("1")
  49. mJSon.json("2")

The justification for using self annotations here is flexibility. A couple other solutions would be
  1. Use subclassing - this is poor solution because there would be an explosion of classes. Instead of having 5 traits you would need 7 traits. Properties, XmlProperties, JSonProperties, XmlStreamProperties, XmlMapProperties, JsonStreamProperties and JsonMapProperties. And if you later wanted to add a new type of properties or a new source like reading from a database then you need 2 new subclasses.
  2. Composition - Another strategy is to use construct the XmlProperties with a strategy that reads from the source. This is essentially the same mechanism except that you need to build and maintain the the dependencies. It also makes layering more difficult. For example:
    1. trait IterableXmlProperties {                                            
    2.     self : MapProperties with XmlProperties => 
    3.     def xmlIterable = source.keySet map {xml _}
    4.   }
    6.   new XmlProperties with MapProperties with IterableXmlProperties {def source = sampleMap}

The next question that comes to mind is why use extends then if self annotation is so flexible? My answer (and I welcome discussion on this point) has three points.
  1. The first is of semantics and modeling. When designing a model it is often more logical to use inheritance because of the semantics that comes with inheriting from another object.
  2. Another argument is pragmatism.
    Imagine the collections library where there is no inheritance. If you wanted a map with Iterable functionality you would have to always declare Traversable with Iterable with Map (and this is greatly simplified). That declaration would have to be used for virtually all methods that require both the Iterable and Map functionality. To say that is impractical is an understatement. Also the semantics of Map is changed from what it is now. The trait Map currently includes the concept of Iterable.
  3. The last point is sealed traits/classes. When a trait is "sealed" all of its subclasses are declared within the same file and that makes the set of subclasses finite which allows certain compiler checks. This (as far as I know) cannot be done with self annotations.


  1. I am not sure this is the most convincing example for using self types. First off, you could replace both

    { self : Properties =>


    extends Properties {

    Also, from a modeling perspective, wouldn't it make more sense to switch the self type and inheritance, i.e. have XmlProperties and JSonProperties use self types (since they require the apply method) an have StreamProperties and MapProperties use inheritance (since they supply it)?

  2. How can yo express more than one dependency?

    I tried with

    (dep1: Dep1, dep2: Dep2) => {

    and it compiles, but it doesn't enforce the dependecies...

  3. opensas:
    scala> class Bar
    defined class Bar

    scala> trait Foo
    defined trait Foo

    scala> class FooBar { self: Bar with Foo => }
    defined class FooBar