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

Mic*_*l K 3 generics scala typeclass

我想编写一个通用类,该通用类包含一个范围的端点,但是通用版本会引发编译错误: 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

具体版本按预期工作:

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
Run Code Online (Sandbox Code Playgroud)

Lui*_*rez 7

你太近了

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)
}
Run Code Online (Sandbox Code Playgroud)