Java 8 lambdas执行

Java 8中如何做这样的事情?

boolean x = ((boolean p)->{return p;}).apply(true);

现在我得到以下错误:

The target type of this expression must be a functional interface

根据JLS section 15.27

It is a compile-time error if a lambda expression occurs in a program in someplace other than an assignment context (§5.2), an invocation context (§5.3), or a casting context (§5.5).

也可以在return statement中使用lambda表达式.

然后我们可以用四种不同的方式重写你的例子:

>通过创建一个赋值上下文:

Function<Boolean, Boolean> function = p -> p;
boolean x = function.apply(true);

通过创建一个调用上下文:

foobar(p -> p);

private static void foobar(Function<Boolean, Boolean> function) {
    boolean x = function.apply(true);
}

>通过创建一个转换上下文:

boolean x = ((Function<Boolean, Boolean>) p -> p).apply(true);

>使用return语句:

boolean x = function().apply(true);

private static Function<Boolean, Boolean> function() {
    return p -> p;
}

另外,在这个简单的例子中,整个lambda表达式可以重写为:

UnaryOperator<Boolean> function = UnaryOperator.identity();
翻译自:https://stackoverflow.com/questions/32383699/java-8-lambdas-execution

转载注明原文:Java 8 lambdas执行