Consider the following Scala code:
package scala_java
object MyScala {
def setFunc(func: Int => String) {
func(10)
}
}
Now in Java, I would have liked to use MyScala
as:
package scala_java;
public class MyJava {
public static void main(String [] args) {
MyScala.setFunc(myFunc); // This line gives an error
}
public static String myFunc(int someInt) {
return String.valueOf(someInt);
}
}
However, the above does not work (as expected since Java does not allow functional programming). What is the easiest workaround to pass a function in Java? I would like a generic solution that works with functions having arbitrary number of parameters.
EDIT: Does Java 8 have any better syntax than the classic solutions discussed below?
In the
scala.runtime
package, there are abstract classes namedAbstractFunction1
and so on for other arities. To use them from Java you only need to overrideapply
, like this:If you're on Java 8 and want to use Java 8 lambda syntax for this, check out https://github.com/scala/scala-java8-compat.
The easiest way for me is to defined a java interface like:
Then modify your scala code, overloading
setFunc
to accept alsoJFunction
objects such as:You will naturally use the first definition from scala, but still be able to use the second one from java:
Here's my attempt at a solution, a little library: https://github.com/eirslett/sc8
You wrap your Java 8 lambda in F(...) and then it's converted to a Scala function.
You have to manually instantiate a
Function1
in Java. Something like:This is taken from Daniel Spiewak’s “Interop Between Java and Scala” article.