Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala from Java: passing functions as parameters

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?

like image 527
Jus12 Avatar asked Jul 01 '11 07:07

Jus12


People also ask

How do you pass a function to a function in Scala?

One function can be passed to another function as a function argument (i.e., a function input parameter). The definition of the function that can be passed in as defined with syntax that looks like this: "f: Int > Int" , or this: "callback: () > Unit" .

Can we call Scala from Java and Java from Scala?

Scala classes are Java classes, and vice versa. You can call the methods of either language from methods in the other one. You can extend Java classes in Scala, and vice versa. The main limitation is that some Scala features do not have equivalents in Java, for example traits.

Does Scala pass by reference?

In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).

How do you call a function in Scala?

In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function.


1 Answers

In the scala.runtime package, there are abstract classes named AbstractFunction1 and so on for other arities. To use them from Java you only need to override apply, like this:

Function1<Integer, String> f = new AbstractFunction1<Integer, String>() {     public String apply(Integer someInt) {         return myFunc(someInt);     } }; 

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.

like image 187
Seth Tisue Avatar answered Oct 17 '22 23:10

Seth Tisue