【发布时间】:2012-03-18 13:43:38
【问题描述】:
我想知道为什么List(3,2,1).toIndexedSeq.sortBy(x=>x) 不起作用:
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)
【问题讨论】:
-
另外,
List(3,2,1).toIndexedSeq.sortBy(identity)给出了一个更有用的错误,List(3,2,1).toIndexedSeq[Int].sortBy(x => x)工作得很好。 -
注意,可以切换 sortBy 和 toIndexedSeq:
List (3, 2, 1).sortBy (x => x). toIndexedSeq
标签: scala scala-collections implicit