I'm attempting to use abstract typing to simplify and clarify type handling, but I keep encountering seemingly non-sensical errors like these:
trait Delta[A] {
def apply(c: A)
}
abstract class ValueHolder {
type Value
type Event <: Delta[ValueHolder]
def update(next: Value): Event = new UpdateEvent(next)
// type mismatch; found : UpdateEvent[ValueHolder]
// required: ValueHolder.this.Event
}
class UpdateEvent[C <: ValueHolder](next: C#Value) extends Delta[C] {
def apply(c: C) = c.update(next)
// type mismatch; found :
// UpdateEvent.this.next.type (with underlying type C#Value)
// required: c.Value
}
Doesn't
Delta[C], whereC <: ValueHolder, thus conform toEvent <: Delta[ValueHolder]?Likewise, given that
cis aC, isn'tc.ValueaC#Value?
I can use a cast to remove the second error, but that defeats the point of using types.
I tried to incorporate the answer suggested in [this related question][1]...
class UpdateEvent[C <: ValueHolder, V <: C#Value](next: V) extends Delta[C] {
... which, sadly, fails to alleviate either problem (although it requires a few more type parameters when called from update()).
Help???
Update: Unfortunately, the example I gave above was a bit oversimplified. I'm trying to propagate changes to classes having the same method signatures (though possibly different type parameters), which thus act as "views" of the original.
For example, imagine you could run this:
(ListBuffer[Int]:_).map(_.toString)
... and then have the resulting ListBuffer[String] updated every time the original is. (Without just running "map" over and over, for reasons I can't explain briefly.) As with this tiny example, others define the traits being implemented, meaning I can't change the method signatures to work around the problem.
(NB: I also can't get rid of type Event because there's a variable (not illustrated here) containing all the listeners who receive each Event -- and the type of that should be refined by subclasses to allow more specific kinds of listeners for each.)
Anyway, after much time pondering the not-very-explanatory Scala Reference manual (the information is all there, but it assumes you know a lot already), I finally figured out how to constrain UpdateEvent so that C and C#Value correspond:
class UpdateEvent[V, C <: ValueHolder { type Value = V }](
next: V) extends Delta[C] { ... }
This fixes both compilation errors and preserves the existing approach. But I'm marking Peter's answer (below) as correct (giving him the reputation points) because I so very much appreciate his spending time on it. Thanks, Peter, and best to you.