我刚刚开始学习 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/