Scala中的泛型继承
我试图在Scala中实现Okasaki的书中的一些结构,在测试中,我试图将实际的测试保持在基类中,只使用子类来提供被测试的实例 例如,不平衡(树)集的测试如下所示:Scala中的泛型继承,scala,generics,type-inference,Scala,Generics,Type Inference,我试图在Scala中实现Okasaki的书中的一些结构,在测试中,我试图将实际的测试保持在基类中,只使用子类来提供被测试的实例 例如,不平衡(树)集的测试如下所示: class UnbalancedSetSpec extends SetSpec(new UnbalancedSet[Int]) with IntElements 在哪里 现在,有时我想专门研究儿童规格,例如 class RedBlackSetSpec extends SetSpec(new RedBlackSet[In
class UnbalancedSetSpec
extends SetSpec(new UnbalancedSet[Int])
with IntElements
在哪里
现在,有时我想专门研究儿童规格,例如
class RedBlackSetSpec
extends SetSpec(new RedBlackSet[Int])
with IntElements {
"fromOrdList" should {
"be balanced" ! prop { (a: List[Int]) =>
val s = RedBlackSet.fromOrdList(a.sorted)
set.isValid(s) should beTrue
}
}
}
它失败是因为在
集合[E,s]
上没有方法是有效的
-它是在RedBlackSet[E]
中定义的。但是,如果我继续将SetSpec[E,S](val set:set[E,S])
更改为SetSpec[E,S,SES,这实际上是Scala类型推断的一个众所周知的问题:它不能“先”推断SES
,然后用它来推断E
和S
class RedBlackSetSpec(override val set: RedBlackSet[Int]) extends SetSpec(set) with IntElements {
def this() = this(new RedBlackSet[Int])
...
}
如果将SetSpec
中的set
作为一个抽象val
而不是构造函数参数,但在不需要专门化的情况下进行了一些折衷,那么它就不那么难看了。我认为应该有一个更好的方法,但这应该有效。okasaki.set[E,S]的类型参数的方差是多少
?问得好!集[E,S]
本身是不变的;RBTree[+E]
是协变的(允许对象为空扩展RBTree[无]
)。
Error:(7, 11) inferred type arguments [Nothing,Nothing,okasaki.RedBlackSet[Int]] do not conform to class SetSpec's type parameter bounds [E,S,SES <: okasaki.Set[E,S]]
extends SetSpec(new RedBlackSet[Int])
^
Error:(7, 11) inferred type arguments [Nothing,Nothing,okasaki.UnbalancedSet[Int]] do not conform to class SetSpec's type parameter bounds [E,S,SES <: okasaki.Set[E,S]]
extends SetSpec(new UnbalancedSet[Int])
^
package okasaki
class RedBlackSet[E](implicit ord: Ordering[E]) extends Set[E, RBTree[E]] {
class RedBlackSetSpec
extends SetSpec[Int, RedBlackSet.RBTree[Int], RedBlackSet[Int]](new RedBlackSet[Int])
with IntElements {
class UnbalancedSetSpec
extends SetSpec[Int, BinaryTree[Int], UnbalancedSet[Int]](new UnbalancedSet[Int])
with IntElements
class RedBlackSetSpec(override val set: RedBlackSet[Int]) extends SetSpec(set) with IntElements {
def this() = this(new RedBlackSet[Int])
...
}