Scala中的通用继承
发布时间:2020-12-16 08:51:14 所属栏目:安全 来源:网络整理
导读:我正在尝试从 Scala中的Okasaki的书中实现一些结构,并且在测试中尝试将实际测试保留在基类中,仅使用子类来提供测试中的实例. 例如,对不平衡(树)集的测试如下所示: class UnbalancedSetSpec extends SetSpec(new UnbalancedSet[Int]) with IntElements 哪里
我正在尝试从
Scala中的Okasaki的书中实现一些结构,并且在测试中尝试将实际测试保留在基类中,仅使用子类来提供测试中的实例.
例如,对不平衡(树)集的测试如下所示: class UnbalancedSetSpec extends SetSpec(new UnbalancedSet[Int]) with IntElements 哪里 abstract class SetSpec[E,S](val set: Set[E,S]) extends Specification with ScalaCheck { implicit def elements: Arbitrary[E] // ... private def setFrom(es: Seq[E]): S = es.foldRight(set.empty)(set.insert) } 现在有时我想专门研究儿童规范,例如 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 } } } 它失败了,因为Set [E,S]上没有方法isValid – 它在RedBlackSet [E]中定义.但是如果我继续将SetSpec [E,S](val set:Set [E,S])更改为SetSpec [E,S,SES<:Set [E,S]](val set:SES),特殊问题消失了,但代码仍然无法编译: Error:(7,11) inferred type arguments [Nothing,Nothing,okasaki.RedBlackSet[Int]] do not conform to class SetSpec's type parameter bounds [E,SES <: okasaki.Set[E,S]] extends SetSpec(new RedBlackSet[Int]) ^ Error:(7,okasaki.UnbalancedSet[Int]] do not conform to class SetSpec's type parameter bounds [E,S]] extends SetSpec(new UnbalancedSet[Int]) ^ RedBlackSet的定义如下: package okasaki class RedBlackSet[E](implicit ord: Ordering[E]) extends Set[E,RBTree[E]] { 所以我希望E被推断为Int而不是Nothing,而S作为RBTree [Int] – 但它不会发生. 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 工作得很好,但看起来很难看. 我很难理解为什么E和S在这里没有被推断出来.任何提示? 解决方法
这实际上是Scala类型推断的一个众所周知的问题:它无法推断SES“第一”并用它来推断E和S.一个解决方案浮现在脑海:
class RedBlackSetSpec(override val set: RedBlackSet[Int]) extends SetSpec(set) with IntElements { def this() = this(new RedBlackSet[Int]) ... } 如果你在SetSpec中设置一个抽象的val而不是一个构造函数参数,那就变得不那么难看了,但是在你不需要专门化的情况下稍微权衡一下.我认为应该有一个更好的,但这应该有效. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |