java - Java 中的 Lambda 表达式给出 "invalid tokens"语法错误

标签 java arguments java-8 lambda

我刚刚开始学习 Lambda 表达式,我做了这样的事情:

public class LambdaTest {

    public static void main(String[] args) {
        int num = returnNumber((num) -> { return 4 });
    }

    public static int returnNumber(int num) {
        return num;
    }
}

但它给了我一个错误:“无效的 token ”。这是一张图片:

有人可以解释一下我出了什么问题吗?这只是一个测试。

我的 Eclipse 安装 (Luna 4.4) 支持 Java 1.8。

最佳答案

There are a few restrictions on what can be done in the body of the lambda, most of which are pretty intuitive—a lambda body can’t “break” or “continue” out of the lambda, and if the lambda returns a value, every code path must return a value or throw an exception, and so on. These are much the same rules as for a standard Java method, so they shouldn’t be too surprising.

引用:http://www.oracle.com/technetwork/articles/java/architect-lambdas-part1-2080972.html

The method's body has the effect of evaluating the lambda body, if it is an expression, or of executing the lambda body, if it is a block; if a result is expected, it is returned from the method.

If the function type's result is void, the lambda body is either a statement expression or a void-compatible block.

引用:http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4

关于java - Java 中的 Lambda 表达式给出 "invalid tokens"语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321884/

相关文章:

Java消费者接口(interface)

java - 使用 Spring mvc 和 MockMVC 上传文件

java - Mime 类型设置不正确

java - 类型中的方法不适用于参数

java - 原因 : inferred type does not conform to upper bound(s)

java - 在 Java 8 中使用Optional.empty 默认可选 orElse

java - 根据 HTTP 规范, '*' 是内容类型的有效通配符吗?

Java 程序错误与 tostring

javascript - HackReactor,编码窗口现在可以使用名为 "Admissions"的方法访问名为 "showApp"的对象。不带任何参数调用此方法?

c - 二维动态数组未初始化 - 函数 C 的参数