简体   繁体   中英

Scala - root of covariant type hierarchy

The following Scala class:

class Foo[+T <: Bar] extends FooBase ...

effectively defines a type hierarchy which has Foo[Bar] as its root - ie any valid Foo[X] will be assignable to a Foo[Bar] value or variable:

val v1: Foo[Bar] = new Foo[SubBar1]();
val v2: Foo[Bar] = new Foo[SubBar2]();

FooBase is further up and could also imply objects that are not Foo - the following shows the issue:

class Trouble extends FooBase ...
val iOnlyWantFooHere: FooBase = new Trouble();

... and also FooBase is not aware of type T, so its members cannot specify it and I'd have to override these definitions in Foo to specialize them:

class FooBase {
  def ohNoIDontKnowTheType: Bar;
}

class Foo[+T <: Bar] extends FooBase {
  override def ohNoIDontKnowTheType: T = ...;
}

There are other ways to work around that issue, but the point should be clear.

Finally, my actual question is what is the root of the following hierarchy:

class Foo[+T <: Foo[T]] extends FooBase ...

Again, do not tell me FooBase, because that is not the case. Yes, I could insert another class in between specifically for the purpose, but that is still not a true answer as indicated above.

Scala does not like just Foo (without the type parameter), and it is not Foo[_] either as then accessing methods returning the value of the type parameter type will actually be Any , not Foo . Of course, we cannot do Foo[Foo] either since that is also missing the type parameter for the second one and Foo[Foo[_]] or Foo[Foo[Foo[Foo[_]]] only gets us so many levels.

Is there an answer at all or does Scala lack support for this?

Thanks in advance!

How about Foo[_ <: Foo[_]] ? Which, by the way, I did mention in my answer to your other question. Or you could write it like this:

type Base = Foo[t] forSome { type t <: Foo[t] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM