0

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
vikash srivastava
  • 393
  • 2
  • 4
  • 16
  • The body of your lambda expression is totally harmful. You are catching all `Exception`s, but then silently ignore them (for your `catch` block is empty). The exceptions would be swallowed anyway, because you have a `return` inside your `finally` block. You [shouldn't do that](https://stackoverflow.com/a/48740/507738). – MC Emperor Oct 17 '20 at 10:32
  • Regarding the error you're getting: you define the return type of `executeCode` to be a `T`, but you're trying to return some implementation of a functional interface. However, `T` can be any type, so the lambda expression cannot conform to `T`. – MC Emperor Oct 17 '20 at 10:36

1 Answers1

1

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);
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41