Tuesday 28 June 2016

Explicitly-typed-self vs. Inheritance

In Scala it is possible to tie a class to another type (which will be implemented in future) by giving self reference self the other type explicitly.

trait T {
  self : T2 =>
  ...
}
In the body, self is an alias for this but has the more precise type T with T2.
The trait T has been mixed in to an appropriate type, and makes those methods available.
Although both the explicit self-type annotation and the simple extends keyword describe an "is-a" relationship between two types, that relationship is not externally visible in the explicit self-type.

trait T
class C {this: T =>}
implicitly[C <:< T]

In the cake pattern you don't want your "module" object to be inadvertently, polymorphically used as one of the traits on which it depends.
When you use inheritance, you make decisions about initialization order. When you use self types, you leave that open.


Reference:
http://docs.scala-lang.org/tutorials/tour/explicitly-typed-self-references.html

No comments:

Post a Comment