views:

1434

answers:

5

Hi all,

Can someone please tell me if there is an equivalent for Python's lambda functions in Java?

+3  A: 

One idea is based on a generic public interface Lambda<T> -- see http://www.javalobby.org/java/forums/t75427.html .

Alex Martelli
+4  A: 

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.

Can Your Programming Language Do This?

nategood
+12  A: 

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 :(

Zifre
Lambda can take and will return a value. You want something more like Callable.
Dustin
In addition to being able to accept parameters and return values, lambdas can also access local variables in the scope they were defined. In Java, anonymous classes can access final variables in the scope they were defined in, which is similar enough. OTOH, it might be a good idea for Something to implement Callable.
gooli
Yes, I know about Callable, but I wanted to show the "general" way.
Zifre
A: 

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.

A: 

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

Asteroth