2012-02-29 45 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