The singleton types and ETSR's do not solve the problem. I myself was looking for just the same feature in Scala, but apparently it lacks the so-called self-type annotations.
There are circumstances where such self-type annotations could be very useful. Consider an example (adapted from Circular type parameters question example):
// we want a container that can store elements
trait Container[E <: Element[E]] {
def elements: Seq[E]
def add(elem: E): Unit
}
// we want elements be aware of their enclosing container
trait Element[E <: Element[E]] {
def container: Container[E]
}
Let's say you put that into a library. A library consumer should do the following:
object PersonContainer extends Container[Person] {
// actual implementation is not important
def elements = Nil
def add(p: Person) = {}
}
class Person extends Element[Person] { // {1}
def container = PersonContainer
}
It is allright and everything works quite as expected. The only thing that concerns is that a library consumer is supposed to use the self-bound type parameter (#1 in the code). But that's not all. Now suppose you have some sort of an ActiveRecord pattern in mind, and you want to add the method save
to Element
, which just delegates to it's container's add
method. Surprisingly, it is not that easy:
trait Element[E <: Element[E]] {
def container: Container[E]
def save() = container.add(this) // won't compile
}
found : Element[E]
required: E
Intuitively, we have a few options here:
- make
add
method accept Element[E]
instead of E
;
- cast
this
to Element[E]
.
None of these options are satisfactory, just because of the fact that E
is not the same as Element[E]
(implementations are not forced to use self-bound type parameters). The only way I see of solving this problem is to have that self-type concept in Scala (let's suppose we have it in our favorite language):
trait Container[E <: Element] {
def elements: Seq[E]
def add(elem: E): Unit
}
trait Element { // the type parameter would be redundant ...
def save() = container.add(this) // ... and this would be possible, too, ...
def container: Container[this] // ... if only we could do this
}
If the compiler could treat this
(or maybe another keyword), when it is used inside square brackets, as the type of the actual implementation (i.e. the same type as the result of obj.getClass
), then the problems would disappear.
P.S. May someone consider including this stuff into Scala wishlist? Unfortunately, I don't know, how hard it is to implement such logic since there could be the problems with the notorious JVM's erasure.
P.P.S. Or maybe there is some another Scala-way I'm unaware of?