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

+0

sortByとtoIndexedSeq: 'List(3、2、1).sortBy(x => x)を切り替えることができます。 toIndexedSeq' –

答えて

6

あなたはListtoIndexedSeqの型シグネチャを見ればあなたはそれが取る表示されますあなたは型パラメータは、コンパイラは、基本的に可能な限り最も具体的なタイプを取って、あなたは何を意味するのかを推測する必要があることを除外した場合

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

Aの任意のスーパータイプすることができtypeパラメータB、 。 List(3,2,1).toIndexedSeq[Any]を意味する可能性があります。Ordering[Any]がないため、ソートすることはできません。コンパイラは、式全体が正しい型付け(コンパイラ内部について何かを知っている人がこれを拡張できる)をチェックされるまで、「推測型パラメータ」を再生しないようです。

:あなたはどちらかa)はすなわち必要な型パラメータに

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

またはb)式のパラメータはsortByを呼び出す前に推論する必要があるように、2つに表現を分離し、自分自身を提供することができます

それを動作させるために

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

編集:

それはおそらくですはFunction1引数をとります。 sortByの署名がsortedに対し

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

である(あなたの代わりに使用する必要があります!)List(3,2,1).toIndexedSeq.sorted

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

で正常に動作します私は正確な理由Function1は、この問題の原因はわからないと私はするつもりですそれでそれについてもっと考えることはできません。

+0

は2.10以降で動作します。 –