如何比较通用枚举值?

时间:2019-05-01 17:46:27

标签: scala scala-2.12

我正在尝试为Scala Enumeration值编写一个通用的max方法。我有

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
}

但是我收到了相当神秘的错误消息

[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]                                                                     ^

有人知道这里发生了什么吗?有没有更好的方法可以做到这一点?谢谢。

相关问题:Deriving a Cats Order for Scala's Enumeration

2 个答案:

答案 0 :(得分:5)

添加上下文绑定的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
}

只是编译器错误消息并不清楚。


尝试

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
}

答案 1 :(得分:4)

您可以像这样编写通用的max

def max[T](a: T, b: T)(implicit ord: Ordering[T]) =
  if (ord.compare(a, b) >= 0) { a } else { b }

如果愿意,可以限制受支持的类型,但是尚不清楚这是否特别有用。

def maxEnum[T <: Enumeration#Value](a: T, b: T)(implicit ord: Ordering[T]) =
  if (ord.compare(a, b) >= 0) { a } else { b }
相关问题