Scala - 协变类型层次结构的根
下面的 Scala 类:
class Foo[+T <: Bar] extends FooBase ...
有效地定义了一个以 Foo[Bar] 作为根的类型层次结构 - 即任何有效的 Foo[X] 都可以分配给 Foo[Bar] 值或变量:
val v1: Foo[Bar] = new Foo[SubBar1]();
val v2: Foo[Bar] = new Foo[SubBar2]();
FooBase 更靠上,也可以暗示对象不是 Foo - 以下显示了问题:
class Trouble extends FooBase ...
val iOnlyWantFooHere: FooBase = new Trouble();
...而且 FooBase 也不知道类型 T,因此它的成员无法指定它,我必须重写 Foo 中的这些定义来专门化它们:
class FooBase {
def ohNoIDontKnowTheType: Bar;
}
class Foo[+T <: Bar] extends FooBase {
override def ohNoIDontKnowTheType: T = ...;
}
还有其他工作方法围绕这个问题,但是要点应该很清楚。
最后,我的实际问题是以下层次结构的根是什么:
class Foo[+T <: Foo[T]] extends FooBase ...
同样,不要告诉我 FooBase,因为事实并非如此。是的,我可以专门为此目的在中间插入另一个类,但这仍然不是上面指出的真正答案。
Scala 不喜欢 Foo
(没有类型参数),也不是 Foo[_]
,因为访问返回类型参数 type 的值的方法实际上会是 Any
,而不是 Foo
。当然,我们也不能执行 Foo[Foo]
,因为这也缺少第二个和 Foo[Foo[_]]
或 Foo 的类型参数[Foo[Foo[Foo[_]]]
只能为我们提供这么多级别。
有没有答案或者 Scala 缺乏对此的支持?
提前致谢!
The following Scala class:
class Foo[+T <: Bar] extends FooBase ...
effectively defines a type hierarchy which has Foo[Bar] as its root - i.e. 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Foo[_ <: Foo[_]]
怎么样?顺便说一句,我在回答你的另一个问题时确实提到了这一点。或者你可以这样写: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: