Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala枚举值未排序?_Scala_Enums - Fatal编程技术网

Scala枚举值未排序?

Scala枚举值未排序?,scala,enums,Scala,Enums,scala文档说Enumeration.Val是有序的,但是当我试图对枚举值强制类型限制要求它们支持排序时,会出现不一致的行为: object Dogs extends Enumeration { val Sam, Tom, Rover = Value } def doSomething[A <% Ordered[A]](a : List[A]) : Unit = { println(a.sortWith(_ < _)) } import Dogs._ val

scala文档说Enumeration.Val是有序的,但是当我试图对枚举值强制类型限制要求它们支持排序时,会出现不一致的行为:

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 =(

我如何绕过这个问题,在需要排序的通用方法中使用枚举值?

问题是
Value
实现
Ordered[enumeration\Value]
,而不是
Ordered[Dogs.Value]
。我不知道这样做的理由,不可能用另一种方式

这对于直接比较两个值的简单情况就足够了——这只是一个普通的方法调用:

scala> (Rover: Ordered[Enumeration#Value]).<(Sam)
res44: Boolean = false
或者,通过将类型参数显式传递给
doSomething

scala> doSomething[Enumeration#Value](List(Rover, Sam))                          
List(Sam, Rover)
或者,更好的办法是放松对类型参数的要求,在这种情况下,本质上将
有序
视为逆变

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>def doSomething[A:A]](xs:List[A])=xs sortWith
doSomething[A](xs:List[A])(隐式证据$1:(A)=>有序的[A])列表[A]
scala>剂量测量(列表(漫游者、Sam))
res47:List[Dogs.Value]=列表(山姆、罗孚)
为什么会这样

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

scala>Rover:Ordered[uu感谢@retronym,最后一个例子解决了我的问题,尽管我的思维受到了较弱的类型限制!现在它需要任何类型A,只要A可以被视为(即是,或可以转换为)由A的泛化排序的东西。这是正确的吗?
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