1

The line

private val keyComparator = util.Comparator.comparing[(String, String), String]((p: (String, String)) => p._1)

produces the error

[error] ...: overloaded method value comparing with alternatives:
[error]   (x$1: java.util.function.Function[_ >: (String, String), _ <: String])java.util.Comparator[(String, String)] <and>
[error]   (x$1: java.util.function.Function[_ >: (String, String), _ <: String],x$2: java.util.Comparator[_ >: String])java.util.Comparator[(String, String)]
[error]  cannot be applied to (((String, String)) => String)
[error]   private val keyComparator = util.Comparator.comparing[(String, String), String]((p: (String, String)) => p._1)
[error]                                                        ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 0 s, completed Jul 30, 2018 12:05:01 PM

If I try to simplify

private val keyComparator = util.Comparator.comparing[(String, String), String](_._1)

I have another error

[error] /home/shu/workspace/kookaburra/src/main/scala/rakuten/kookaburra/util/GrpQuery.scala:41: missing parameter type for expanded function ((x$5: <error>) => x$5._1)
[error]   private val keyComparator = util.Comparator.comparing[(String, String), String](_._1)
[error]                                                                                   ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Jul 30, 2018 12:24:53 PM

What am I doing wrong? Scala 2.12.6. For me it seems like a compiler bug.

1 Answer 1

1

The problem is that java.util.Comparator.comparing needs a java.util.function.Function and you are writing (p: (String, String)) => p._1, which is a scala.Function1.

For some reason a scala lambda doesn't compile to java Function unless you ask to do that explicitly.

Otherwise you need to use java.util.function.Function or an implicit conversion between java Function and scala Function1.

Here you are an implicit convertion example

implicit def sf2jf[T,R](f:(T) => R):java.util.function.Function[T, R] = (t: T) => f(t)
Sign up to request clarification or add additional context in comments.

1 Comment

I tried again, with scala 2.12.2 and 2.12.6. If I assign a scala lambda to java Function works, but I can't do that directly with Comparator unless I create a convertion or save the lambda in a variable java Function.

Your Answer

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