【发布时间】:2012-02-13 15:25:37
【问题描述】:
鉴于下面的代码,foo 方法应该比较operator-wise给定参数bar 与lowerBound 和upperBound 都属于相同的抽象类型Bar。
trait Foo {
type Bar <: Ordered[Bar]
val lowerBound: Bar
val upperBound: Bar
def foo(bar: Bar) = bar >= lowerBound && bar <= upperBound
}
这样可以定义特征Foo。问题从下面的具体类FooImpl开始。
class FooImpl extends Foo {
type Bar = Int
val lowerBound = 0
val upperBound = 5
}
我知道scala.Int 没有实现scala.runtime.RichInt 所做的事情,实际上是scala.math.Ordered[Int]。将类型 Bar 定义为 RichInt 而不是不起作用,因为它不符合 scala.math.Ordered[RichInt]。我第三次尝试将Bar 类型定义为Ordered[Ord],其中Ord 被声明为type Ord,并在FooImpl 中将其定义为Int 也不起作用。
一个可能接近的解决方案是什么样的?
【问题讨论】:
标签: scala abstract-type