简体   繁体   中英

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:

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 !

What is the problem?

Since there is no such thing as a negative String , you can't sort by it. 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 .

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

The error occurs, because - method is not defined on String . The following works just fine:

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

It's because - is defined for Int .

Maybe you meant something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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