[英]scala type bounds and variance
Please explain what princeples of scala typing and why should be use here请解释什么是 Scala 打字的原则以及为什么应该在这里使用
I got type hierarchy我有类型层次结构
class A
class B extends A
class C extends A
cladd D extends C
And other type class和其他类型类
class Hub(init) {
def add(elem): Hub = new Hub(elem)
}
I need to do edit typing of Hub
and Hub.add
that it should work like this我需要编辑
Hub
和Hub.add
输入,它应该像这样工作
val a : Hub[D] = Hub(new D)
val b : Hub[A] = a.add(new B)
val c : Hub[A] = b.add(new C)
val d : Hub[A] = c.add(new D)
And this should be compile error这应该是编译错误
val e : Hub[C] = b.add(new C)
how should I edit it and why?我应该如何编辑它,为什么?
PS This is not valid scala code, it is for sake of types example PS 这不是有效的 Scala 代码,这是为了类型示例
Make add
parametric with proper type bounds [B >: A]
(see like half the standard library collections' methods for typical examples).使用适当的类型边界
add
参数[B >: A]
(典型示例参见标准库集合的一半方法)。
class Hub[A](a: A) {
def add[B >: A](b: B): Hub[B] = new Hub[B](b)
}
object Hub {
def apply[A](a: A): Hub[A] = new Hub[A](a)
}
val a : Hub[D] = Hub(new D)
val b : Hub[A] = a.add(new B)
val c : Hub[A] = b.add(new C)
val d : Hub[A] = c.add(new D)
// val e : Hub[C] = b.add(new C) type mismatch
In [B >: A](b: B)
compiler tries to infer B
s that it would both:在
[B >: A](b: B)
编译器试图推断B
s 它会同时:
A
A
的超类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.