Scala Enumeration values ​​not ordered?

The scala docs say that Enumeration.Val is streamlined, however I get inconsistent behavior when trying to enforce type constraints on enum values ​​that require their support:

object Dogs extends Enumeration {
    val Sam, Tom, Rover = Value
}

def doSomething[A <% Ordered[A]](a : List[A]) : Unit = {
    println(a.sortWith(_ < _))
}

import Dogs._

val xs = List(Rover, Tom, Sam, Sam, Rover)

println(xs.sortWith(_ < _))  // works!
doSomething(xs)              // fails =(

Of the last two statements, the first works and shows that Enumeration values ​​have a given ordering. The second gives an error:

could not find implicit value for evidence parameter of type (this.Dogs.Value) => Ordered[this.Dogs.Value]

How do I get around this and use enumeration values ​​in common methods that require ordering?

+5
source share
1 answer

The problem is what Valueperforms Ordered[Enumeration#Value], not Ordered[Dogs.Value]. I do not know the reason for this, it is impossible to do it any other way.

- :

scala> (Rover: Ordered[Enumeration#Value]).<(Sam)
res44: Boolean = false

A Ordered , , param Ordered[A], Dogs.Value <: Ordered[Enumeration#Value]. A , , .

, Enumeration#Value:

scala> val xs = List[Enumeration#Value](Rover, Tom, Sam, Sam, Rover)
xs: List[Enumeration#Value] = List(Rover, Tom, Sam, Sam, Rover)

scala> doSomething(xs)                 
List(Sam, Sam, Tom, Rover, Rover)

, doSomething:

scala> doSomething[Enumeration#Value](List(Rover, Sam))                          
List(Sam, Rover)

, , , Ordered .

scala> def doSomething[A <% Ordered[_ >: A]](xs : List[A]) = xs sortWith (_ < _)
doSomething: [A](xs: List[A])(implicit evidence$1: (A) => Ordered[_ >: A])List[A]

scala> doSomething(List(Rover, Sam))                                            
res47: List[Dogs.Value] = List(Sam, Rover)

?

scala> Rover: Ordered[_ <: Enumeration#Value]
res52: scala.math.Ordered[_ <: Enumeration#Value] = Rover
+8

All Articles