here's how lambdas are in kotlin -
val myLambda: (Int, Int) -> Unit = { a, b ->
Log.d(TAG, "sum value = ${a b}")
}
myLambda(1, 2)//running the lambda
In java, I found these two methods to do the same.
Here, I can't have the runnable take a parameter.
// runnable method
Runnable runnable = () -> {
System.out.println("x");
};
runnable.run();
The issue with this method is I would have to declare multiple interfaces for different types
// interface method
Finder finder = (s1, s2) -> s1.indexOf(s2);
System.out.println(finder.find("1234", "23"));
public interface Finder {
public int find(String s1, String s2);
}
So, the question I have is whether there is an easier way to implement lambda in java better that both of these.
Note - I'm new to java.
CodePudding user response:
No. Java does not have function types built into the language. You must have an interface for every lambda you define.
...or you can use the built-in ones, which are sufficient for many use cases. This, for example, might be a ToIntBiFunction<String, String>
.
CodePudding user response:
Since Java 8, there is the Generic Function interface. It allows you to store lambda functions.