I would like to create an implicit conversion from a Scala function (possibly anonymous) to java.util.function.Function
. Here is what I have:
import java.util.function.{Function => JavaFunction}
implicit def scalaFunctionToJavaFunction[From, To](function: (From) => To): JavaFunction[From, To] = {
new java.util.function.Function[From, To] {
override def apply(input: From): To = function(input)
}
}
It works fine except that the type inference fails when the function being converted doesn't specify parameter type explicitly:
val converted: JavaFunction[String, Int] = (s: String) => s.toInt // works fine
val converted2: JavaFunction[String, Int] = scalaFunctionToJavaFunction(s => s.toInt) // works
val converted3: JavaFunction[String, Int] = s => s.toInt // gives compilation error "missing parameter type"
The compiler is able to infer the type
My questions are:
- Why cannot Scala compiler infer type of the parameter in the third case?
- Can I modify the implicit conversion so that the type gets inferred?
I'm aware of a related question which touches on this subject but doesn't give an answer to my questions.
The problem doesn't seem to be related to interoperability with Java, btw. If I replace JavaFunction
with a custom Scala trait, the behavior remains the same.