Generic way to check if range contains value in Scala

泪湿孤枕 提交于 2020-03-19 06:45:52

问题


I'd like to write a generic class that holds the endpoints of a range, but the generic version kicks back a compilation error: 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)
  }
}

The specific version works as expected:

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

回答1:


You were too close.

In Scala we have Ordering, which is a typeclass, to represent types that can be compared for equality and less than & greater than.

Thus, your code can be written like this:

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


来源:https://stackoverflow.com/questions/58469028/generic-way-to-check-if-range-contains-value-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!