Hi all,
Can someone please tell me if there is an equivalent for Python's lambda functions in Java?
Hi all,
Can someone please tell me if there is an equivalent for Python's lambda functions in Java?
One idea is based on a generic public interface Lambda<T>
-- see http://www.javalobby.org/java/forums/t75427.html .
I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only java are missing out on these beauties of functional style programming.
Unfortunately, there are no lambdas in Java. However, you can get almost the same effect (in a really ugly way) with anonymous classes:
interface MyLambda {
void theFunc(); // here we define the interface for the function
}
public class Something {
static void execute(MyLambda l) {
l.theFunc(); // this class just wants to use the lambda for something
}
}
public class Test {
static void main(String[] args) {
Something.execute(new MyLambda() { // here we create an anonymous class
void theFunc() { // implementing MyLambda
System.out.println("Hello world!");
}
});
}
}
Obviously these would have to be in separate files :(
Somewhat similarly to Zifre's, you could create an interface thus
public interface myLambda<In, Out> {
Out call(In i);
}
to enable you to write, say
Function<MyObj, Boolean> func = new Function<MyObj, Boolean>() {
public Boolean callFor(myObj obj) {
return obj.canDoStuff();
};
MyObj thing = getThing;
if (func.callFor(thing)) {
doSomeStuff();
} else {
doOtherStuff();
}
It's still a bit kludgy, yeah, but it has input/output at least.
I need lambda function too, it must be defined and executed in the same expression. Something like: int a = int(int prm) {return prm;}; Is it possible? Thanks