问题
I'm trying to writing a generic max method for Scala Enumeration
values. I have
def enumMax[E <: Enumeration, V <: E#Value](v1: V, v2: V): V = v1.compare(v2) match {
case x if x > 0 => v1
case x if x < 0 => v2
case _ => v1
}
but I'm getting the rather cryptic error message
[error] overloaded method value compare with alternatives:
[error] ((that: _1.Value)Int) forSome { val _1: E } <and>
[error] (that: _1.Value)Int
[error] cannot be applied to (V)
[error] def enumMax[E <: Enumeration, V <: E#Value](v1: V, v2: V): V = v1.compare(v2) match {
[error] ^
Does anybody know what's going on here? Is there a better way to accomplish this? Thanks.
Connected question: Deriving a Cats Order for Scala's Enumeration
回答1:
You can write a generic max
like this:
def max[T](a: T, b: T)(implicit ord: Ordering[T]) =
if (ord.compare(a, b) >= 0) { a } else { b }
If you want to you can constrain the types that are supported, but it is not clear that this is particularly useful.
def maxEnum[T <: Enumeration#Value](a: T, b: T)(implicit ord: Ordering[T]) =
if (ord.compare(a, b) >= 0) { a } else { b }
回答2:
It's enough to add context bound Ordering
def enumMax[E <: Enumeration, V <: E#Value : Ordering](v1: V, v2: V): V = v1.compare(v2) match {
case x if x > 0 => v1
case x if x < 0 => v2
case _ => v1
}
It was just compiler error message that was not clear.
Try
def enumMax(e: Enumeration)(v1: e.Value, v2: e.Value): e.Value = v1.compare(v2) match {
case x if x > 0 => v1
case x if x < 0 => v2
case _ => v1
}
来源:https://stackoverflow.com/questions/55940394/how-to-compare-generic-enumeration-values