英文:
Getting Error :: The target type of this expression must be a functional interface
问题
我正在尝试实现一个示例库,客户可以使用它来执行他们的代码,为了实现这一目标,我正在使用JAVA的函数式编程特性。
但是遇到了编译错误 **表达式的目标类型必须是函数式接口**
	@FunctionalInterface
	public interface ImplemenetIt<T> {
		public T provideYourImpl();
	}
	
	public class HighOrderFunctionClass<T> {
	
		public T executeCode(ImplemenetIt<T> it, T defaultAnswer) {
			T answer = defaultAnswer;
	
			return () -> { // 在这一行我遇到了错误
				try {
					answer = it.provideYourImpl();
				} catch (Exception ex) {
	
				} finally {
					return answer;
				}
			};
		}
	}
请指出我漏掉了什么。 
英文:
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.
答案1
得分: 1
一个lambda表达式是一个函数式接口的实现。你的方法executeCode()返回一个泛型类型(T),而T不是一个函数式接口,但是方法executeCode()中的代码却尝试返回一个函数式接口。
另外,方法executeCode()的一个参数是一个函数式接口,因此当你调用那个方法时,你可以将一个lambda表达式作为参数传递,例如:
executeCode(() -> null, someDefault)
下面是一个更加“具体”的例子。
public class Tester {
    public static void main(String[] args) {
        HighOrderFunctionClass<String> hofc = new HighOrderFunctionClass<>();
        String someDefault = "我是默认值。";
        ImplemenetIt<String> it = () -> "你好,世界。";
        String result = hofc.executeCode(it, someDefault);
    }
}
英文:
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);
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论