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.
The
call
method of the Callable interface returns a value of typeT
. Your lambda is simply shorthand for the call method, and likewise should return aT
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 iscall
. 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:Or you could use a lambda:
Or even more succinctly:
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'