2012-02-29 46 views
9

当我不知道为什么List(3,2,1).toIndexedSeq.sortBy(x=>x)不起作用:斯卡拉 - 混淆“隐含分歧扩大”错误使用“sortBy”

scala> List(3,2,1).toIndexedSeq.sortBy(x=>x) // Wrong 
<console>:8: error: missing parameter type 
       List(3,2,1).toIndexedSeq.sortBy(x=>x) 
              ^
<console>:8: error: diverging implicit expansion for type scala.math.Ordering[B] 
starting with method Tuple9 in object Ordering 
       List(3,2,1).toIndexedSeq.sortBy(x=>x) 
              ^

scala> Vector(3,2,1).sortBy(x=>x) // OK 
res: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3) 

scala> Vector(3,2,1).asInstanceOf[IndexedSeq[Int]].sortBy(x=>x) // OK 
res: IndexedSeq[Int] = Vector(1, 2, 3) 

scala> List(3,2,1).toIndexedSeq.sortBy((x:Int)=>x) // OK 
res: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3) 
+2

另外,'List(3,2,1).toIndexedSeq.sortBy(identity)'给出了更有用的错误和List(3,2,1)。 toIndexedSeq [Int] .sortBy(x => x)'工作得很好。 – dhg 2012-02-29 03:36:55

+0

请注意,您可以切换sortBy和toIndexedSeq:'List(3,2,1).sortBy(x => x)。 toIndexedSeq' – 2012-02-29 15:14:11

回答

6

如果你看看toIndexedSeq类型签名上List你会看到它需要类型参数B,它可以是任何A父:

def toIndexedSeq [B >: A] : IndexedSeq[B] 

如果您离开了该类型参数则编译器基本上是要猜你的意思,以最具体的类型可能。你可能意思是List(3,2,1).toIndexedSeq[Any],这当然不能被排序,因为没有Ordering[Any]。看起来,编译器在检查整个表达式的正确输入之前不会播放“猜测类型参数”(也许某个知道编译器内部内容的人可以对此进行扩展)。

为了使它工作,你可以一)提供所需的类型参数自己即

List(3,2,1).toIndexedSeq[Int].sortBy(x=>x) 

或者b)表达分成两个,这样的类型参数有调用sortBy之前推断:

val lst = List(3,2,1).toIndexedSeq; lst.sortBy(x=>x) 

编辑:

这可能是因为sortBy需要一个Function1参数。的sortBy签名是

def sortBy [B] (f: (A) => B)(implicit ord: Ordering[B]): IndexedSeq[A] 

sorted(你应该使用!)正常工作与List(3,2,1).toIndexedSeq.sorted

def sorted [B >: A] (implicit ord: Ordering[B]): IndexedSeq[A] 

我不知道确切原因Function1原因这个问题,我要去因此无法进一步思考......

+0

自2.10开始工作。 – 2016-11-21 01:01:54