Java - Passing a method through a parameter

1.6k views Asked by At

I'm trying to create a method that allows me to make use of what I believe is called lambdas, to execute a method over a series of connections.

Here's my code that I've come up with after some research, but it doesn't work:

performGlobalAction(()->{
    // doSomething();
});

You'll also need to see the method I would assume:

private <T> void performGlobalAction(Callable<T> action) {
    for(int i = 0; i < connectionList.size(); i++) {
        connectionList.get(i).performAction(action);
    }
}

This provides the following error:

The method performAction(Callable<T>) in the type Connection is not
applicable for the arguments (() -> {})

The goal of this method is to allow myself to construct a method "on the go" without creating a void for it.

Is this possible? It seems like I've used plenty of statements that have done this before. It seems like this is actually exactly how lambdas statements work.

1

There are 1 answers

8
Kenogu Labz On BEST ANSWER

The call method of the Callable interface returns a value of type T. Your lambda is simply shorthand for the call method, and likewise should return a T value.

Any interface that meets the requirements of a FunctionalInterface can be substituted by a lambda expression. Such an interface will have a single abstract method, one with no default implementation. For your question, the interface is Callable, and the abstract method is call. The lambda expression then acts as the body of that abstract method in an anonymous implementation of that interface.

Let's take as an example a method doStuff(Callable<Integer> stuff). To satisfy this interface, you could give an anonymous class:

doStuff(new Callable<Integer>(){
    public Integer call(){
        return 5;
    }
});

Or you could use a lambda:

doStuff( () -> {
    return 5;
} );

Or even more succinctly:

doStuff( () -> 5 );

If your method doesn't have a return type, perhaps Runnable would be a better fit.

See also: Lambda Expressions (Oracle) - 'Use Standard Functional Interfaces with Lambda Expressions'