首页 > 解决方案 > 检查范围是否包含Scala中的值的通用方法

问题描述

我想编写一个包含范围端点的泛型类,但泛型版本会返回编译错误: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

标签: scalagenericstypeclass

解决方案


你离得太近了。

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)
}

推荐阅读