Using Scala from Java: passing functions as parameters -
consider following scala code:
package scala_java object myscala { def setfunc(func: int => string) { func(10) } }
now in java, have liked use myscala
as:
package scala_java; public class myjava { public static void main(string [] args) { myscala.setfunc(myfunc); // line gives error } public static string myfunc(int someint) { return string.valueof(someint); } }
however, above not work (as expected since java not allow functional programming). easiest workaround pass function in java? generic solution works functions having arbitrary number of parameters.
you have manually instantiate function1
in java. like:
final function1<integer, string> f = new function1<integer, string>() { public int $tag() { return function1$class.$tag(this); } public <a> function1<a, string> compose(function1<a, integer> f) { return function1$class.compose(this, f); } public string apply(integer someint) { return myfunc(someint); } }; myscala.setfunc(f);
this taken daniel spiewak’s “interop between java , scala” article.
Comments
Post a Comment