我想编写一个通用类,该通用类包含一个范围的端点,但是通用版本会引发编译错误: value >= is not a member of type parameter A
final case class MinMax[A <: Comparable[A]](min: A, max: A) {
def contains[B <: Comparable[A]](v: B): Boolean = {
(min <= v) && (max >= v)
}
}
具体版本按预期工作:
final case class MinMax(min: Int, max: Int) {
def contains(v: Int): Boolean = {
(min <= v) && (max >= v)
}
}
MinMax(1, 3).contains(2) // true
MinMax(1, 3).contains(5) // false
你太近了
在Scala中,我们有Ordering
一个typeclass,表示可以比较相等且小于和大于的类型。
因此,您的代码可以这样编写:
// Works for any type A, as long as the compiler can prove that the exists an order for that type.
final case class MinMax[A](min: A, max: A)(implicit ord: Ordering[A]) {
import ord._ // This is want brings into scope operators like <= & >=
def contains(v: A): Boolean =
(min <= v) && (max >= v)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句