Java 8 lambdas执行 [英] Java 8 lambdas execution

查看:108
本文介绍了Java 8 lambdas执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java 8中执行此类操作?

How can I do something like this in Java 8?

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

现在我收到以下错误:

此表达式的目标类型必须是功能接口

The target type of this expression must be a functional interface


推荐答案

根据JLS 第15.27节


如果lambda表达式出现在除分配上下文之外的某个位置的程序中,那么这是一个编译时错误( §5.2),调用上下文(第5.3节)或转换上下文(第5.5节)。

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).

也可以在 返回声明

It is also possible to use a lambda expression in a return statement.

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

We can then rewrite your example in four different ways:


  • 通过创建作业上下文:

  • By creating an assignment context:

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


  • 通过创建调用上下文:

  • By creating an invocation context:

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


  • 通过创建投射上下文:

  • By creating a casting context:

    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表达式可以重写为:

    Also, in this simple example, the whole lambda expression can be rewritten as:

    UnaryOperator<Boolean> function = UnaryOperator.identity();
    

    这篇关于Java 8 lambdas执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆