我想编写一个通用类来保存范围的端点,但通用版本会出现编译错误: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
你们离得太近了。
In Scala我们有Ordering https://www.scala-lang.org/api/current/scala/math/Ordering.html,这是一个类型类 https://tpolecat.github.io/2013/10/12/typeclass.html,表示可以比较相等以及小于和大于的类型。
因此,您的代码可以这样写:
// 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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)