检查范围是否包含 Scala 中的值的通用方法

Generic way to check if range contains value in Scala

我想编写一个包含范围端点的通用 class,但通用版本会返回一个编译错误: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, which is a 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)
}