2

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?

0

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.