检查范围是否在Scala中包含值的通用方法 [英] Generic way to check if range contains value in Scala
本文介绍了检查范围是否在Scala中包含值的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个通用类,该通用类包含一个范围的端点,但是通用版本会引发编译错误: value> =不是类型参数A的成员
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)
}
}
特定版本按预期工作:
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 中,我们 订购
,它是 typeclass ,表示可以比较相等且小于&大于.
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)
}
这篇关于检查范围是否在Scala中包含值的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文