user595334
user595334

Reputation:

Pseudo first class functions in Java?

Below I have a rough implementation of testing a list lambda functions on an integer in Python. I know Java currently doesn't support closures or lambdas (yet), but I'm curious, is this remotely possible in Java?

pos = [lambda x : x > 0, "pos"]
even = [lambda x : x % 2 == 0, "even"]
small = [lambda x : x < 100, "small"]

def pass_test(x, tests):
    if (len(tests) == 0): return []
    else:
        if (tests[0][0](x)): return [tests[0][1]] + pass_test(x, tests[1:])
        else: return pass_test(x, tests[1:])

Upvotes: 1

Views: 363

Answers (2)

Ostap Andrusiv
Ostap Andrusiv

Reputation: 4907

In your case, python function could be mapped to Java like this:

public interface Function { 
    String do(int x); 
}

// ...
Function pos = new Function(){
    public String do(int x) {
        return (x > 0) ? "pos" : "";
    }
}
Function even = new Function(){
    public String do(int x) {
        return (x % 2 == 0) ? "even" : "";
    }
}
Function small = new Function(){
    public String do(int x) {
        return (x < 100) ? "small" : "";
    }
}

// ...

As you see, you'd need a lot more code to do the same simple thing in Java.

Upvotes: 1

Ingo
Ingo

Reputation: 36339

Yes, it is possible, along the lines of:

interface Predicate<A> {
    boolean eval(A argument);
}

Predicate<Integer> gt0 = new Predicate<Integer>() {
    boolean eval(Integer arg) {
        return arg > 0;
    }
};

You see, this is a bit verbose, but it does the job.

Upvotes: 4

Related Questions