2014-12-05 45 views
0

“无效令牌”语法错误我刚开始了解Lambda表达式和我做了这样的事情:Lambda表达式给出的Java

public class LambdaTest { 

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

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

但它给我一个错误:“无效令牌”。以下是图像:

是否有人可以给我解释一下什么是错的?这只是一个测试。

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

+1

你为什么认为这应该起作用? Lambdas可以用来提供*功能接口*方法的实现,其中'int'不是。 – Pshemo 2014-12-05 18:00:29

+0

'returnNumber'将'int'作为参数。你给它一个函数。当然,它会给你一个错误。 (顺便提一句,在问题中包含实际的错误信息要好得多,而不是链接到截图。) – ajb 2014-12-05 18:02:25

+0

是的,你是对的。我一直没有注意。谢谢! – 2014-12-05 18:05:25

回答

0

lambda表达式是用于功能接口的方法只是实现(一个抽象方法接口),但是在

returnNumber(int num) 

lambda表达式的情况下不能使用,因为:

  • int是不是一个功能接口
  • 所以lambda不能用于提供其唯一抽象方法的实现(因为原始类型是原始的 - th没有办法)。

之前lambda表达式执行方法类似

method(SomeInterface si){...} 

你需要或者创造条件,实现这个接口

class MyClass implements SomeInterface{ 
    void method(Type1 arg1, Type2 arg2){ 
     //body 
    } 
} 

... 
MyClass mc = new MyClass(); 
method(md); 

或者通过创建加飞其实现单独的类匿名类

method(new SomeInterface{ 
    void method(Type1 arg1, Type2 arg2){ 
     //body 
    } 
}); 

Lambdas可以通过跳过这个成语来缩短这个过程,让你只关注参数类型和实现。

所以不是

new SomeInterface{ 
    void method(Type1 arg1, Type2 arg2){ 
     //body 
    } 
} 

可以简单的写

(Type1 arg1, Type2 arg2) -> { body } // you can actually shorten it even farther 
            // but that is not important now 
1

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

1

语法错误非常简单。它表示在语句后缺少一个;,除了lambda表达式之外的其他语言,这绝不是别的。如果你写(num) -> { return 4 },在return 4之后必须有一个分号,因为它必须在每个你可以写的地方return 4(我很惊讶为什么没有人能够告诉你)。

你可以用两种方式编写一个返回int的lambda表达式,或者像(num) -> { return 4; }或者简单得多,就是num -> 4(这里没有分号)。

但是,当然,您不能使用lambda表达式作为参数调用returnNumber(int num),因为它期望int而不是功能interface。你的编译器会告诉你,一旦你修复了缺少分号的结构语法错误。