【问题标题】:scala - Confusing "diverging implicit expansion" error when using "sortBy"scala - 使用“sortBy”时混淆“发散隐式扩展”错误
【发布时间】: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 =&gt; x) 工作得很好。
  • 注意,可以切换 sortBy 和 toIndexedSeq:List (3, 2, 1).sortBy (x =&gt; x). toIndexedSeq

标签: scala scala-collections implicit


【解决方案1】:

如果您查看ListtoIndexedSeq 的类型签名,您会发现它需要一个类型参数B,它可以是A 的任何超类型:

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

如果您省略了该类型参数,那么编译器基本上必须猜测您的意思,尽可能采用最具体的类型。你可能指的是List(3,2,1).toIndexedSeq[Any],当然不能排序,因为没有Ordering[Any]。似乎编译器在检查整个表达式的类型是否正确之前不会播放“猜测类型参数”(也许知道编译器内部知识的人可以对此进行扩展)。

要使其工作,您可以 a) 自己提供所需的类型参数,即

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 会导致这个问题,我要睡觉了,所以不能再想了......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2015-03-30
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多