How to compare generic enumeration values?

為{幸葍}努か 提交于 2019-12-12 21:01: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


回答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

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