Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to check if range contains value in Scala

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
like image 616
Michael K Avatar asked Sep 07 '25 05:09

Michael K


1 Answers

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)
}
like image 183
Luis Miguel Mejía Suárez Avatar answered Sep 09 '25 03:09

Luis Miguel Mejía Suárez