Some Name
Some Name

Reputation: 9540

Using Comparator from Scala

What's wrong with using Comparator from Scala? The invocation is not compiled:

java.util.Comparator.comparing(
      new java.util.function.Function[String, java.math.BigInteger] {
        override def apply(t: String) = new java.math.BigInteger(t)
})

https://ideone.com/OdHvBU

The error message is very unclear.

Main.scala:3: error: overloaded method value comparing with alternatives:
  [T, U <: Comparable[_ >: U]](x$1: java.util.function.Function[_ >: T, _ <: U])java.util.Comparator[T] <and>
  [T, U](x$1: java.util.function.Function[_ >: T, _ <: U], x$2: java.util.Comparator[_ >: U])java.util.Comparator[T]
 cannot be applied to (java.util.function.Function[String,java.math.BigInteger])
    java.util.Comparator.comparing(
                         ^

What's wrong with that?

Upvotes: 1

Views: 796

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44992

I have to agree with you: the error message is not very clear.

This here works:

java.util.Comparator.comparing[String, java.math.BigInteger](
  new java.util.function.Function[String, java.math.BigInteger] {
    override def apply(t: String) = new java.math.BigInteger(t)
  }
)

What happens is: for some strange reason it cannot infer what the type parameter U is so that it's Comparable. You have to explicitly write out that you are comparing BigIntegers. I'm not sure about why, but it seems to be a common issue with generic java methods (here is another similar example that I've seen just recently).

Upvotes: 2

Related Questions