简体   繁体   English

Scala 中的排序问题,出现“发散隐式扩展.....”错误。 根据元组的第一个元素但按相反的顺序对元组列表进行排序

[英]Problem with sort in scala, got "Diverging implicit expansion ....." error. Sorting a list of tuples based on its first element but in reverse order

I am trying to sort a list of tuples in Scala, the following code will result in error:我正在尝试在 Scala 中对元组列表进行排序,以下代码将导致错误:

List("a"->1,"b"->2, "c"->3).sortBy(-_._1)

error: diverging implicit expansion for type scala.math.Ordering[B]
starting with method Tuple9 in object Ordering
       List("a"->1,"b"->2, "c"->3).sortBy(-_._1)
                                         ^

but the code below works just fine:但下面的代码工作得很好:

List("a"->1,"b"->2, "c"->3).sortBy(_._1)

res39: List[(String, Int)] = List((a,1), (b,2), (c,3))

The only difference is the negative sign in sortBy !唯一的区别是sortBy的负号!

What is the problem?问题是什么?

Since there is no such thing as a negative String , you can't sort by it.由于没有负String类的东西,因此您无法对其进行排序。 You can reverse-sort element types that can't be negated, either by reversing the sorted results...您可以通过反转排序结果来对无法否定的元素类型进行反向排序...

List("a"->1, "b"->2, "c"->3).sortBy(_._1).reverse

...or by replacing the implicit Ordering with an explicit reversed Ordering . ...或者通过更换隐Ordering有明确的反向Ordering

List("a"->1, "b"->2, "c"->3).sortBy(_._1)(Ordering[String].reverse)

The error occurs, because - method is not defined on String .发生错误,因为-方法未在String定义。 The following works just fine:以下工作正常:

List("a"->1, "b"->2, "c"->3).sortBy(-_._2)

It's because - is defined for Int .这是因为-是为Int定义的。

Maybe you meant something like:也许你的意思是这样的:

List("a"->1, "b"->2, "c"->3).sortBy(-_._1.length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM