我正在尝试定义一个特征来描述基于其他运算符的运算符。像这样的事情:
trait LessThanComparable[T] {
def < (that: T) : Boolean
def > (that: T) = that < this
}
然后我使用它:
class Example(val x : Int) extends LessThanComparable[Example] {
def < (that: Example) = x < that.x
}
但是我得到了这个:值<不是类型参数T的成员
我怎么能说那个和这个是同一类型呢?或者我正在尝试一些不可能的事情?
最佳答案
我想这就是你想要的:
trait LessThanComparable[T <: LessThanComparable[T]] { this: T =>
def <(that: T): Boolean
def >(that: T) = that < this
}
class Example(val x: Int) extends LessThanComparable[Example] {
def <(that: Example) = x < that.x
}
为了能够说that < this
,有两件事必须成立。
that
必须有<
接受T
的方法,或者换句话说,that
必须是LessThanComparable[T]
。我们可以通过说T
来确保这一点必须是 LessThanComparable[T] 的子类,或T <: LessThanComparable[T]
.this
必须是T
。我们可以通过使用 self 类型this: T =>
来确保这一点.
那么,
val a = new Example(5)
val b = new Example(4)
println(a < b) // false
println(a > b) // true
println(b < a) // true
println(b > a) // false
关于scala - 如何用trait来描述算子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539855/