How to compare generic enumeration values?

2019-07-08 04:34发布

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

2条回答
仙女界的扛把子
2楼-- · 2019-07-08 05:24

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
}
查看更多
相关推荐>>
3楼-- · 2019-07-08 05:25

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 }
查看更多
登录 后发表回答