Reputation: 413
I am trying to implement a sample lib using which client can execute their code, to achieve it I am using a functional programming feature of JAVA. But getting compilation error The target type of this expression must be a functional interface
@FunctionalInterface
public interface ImplemenetIt<T> {
public T provideYourImpl();
}
public class HighOrderFunctionClass<T> {
public T executeCode(ImplemenetIt<T> it, T defaultAnswer) {
T answer = defaultAnswer;
return () -> { // At this line I am getting error
try {
answer = it.provideYourImpl();
} catch (Exception ex) {
} finally {
return answer;
}
};
}
}
Please, suggest what I am missing.
Upvotes: 0
Views: 3481
Reputation: 20914
A lambda expression is the implementation of a functional interface. Your method executeCode()
returns a generic type (T
) and T
is not a functional interface but the code in method executeCode()
is trying to return a functional interface.
Also one of the parameters to method executeCode()
is a functional interface, so when you call that method, you can pass a lambda expression as an argument, i.e.
executeCode( () -> return null, someDefault )
Here is a more "concrete" example.
public class Tester {
public static void main(String[] args) {
HighOrderFunctionClass<String> hofc = new HighOrderFunctionClass<>();
String someDefault = "I am the default value.";
ImplemenetIt<String> it = () -> return "Hello world.";
String result = hofc.executeCode(it, someDefault);
}
}
Upvotes: 1