docs.oracle.com lambda表达式示例将无法编译

时间:2014-07-03 13:51:24

标签: java lambda

我一直在使用docs.oracle.com作为学习java的方法,当我尝试编译下面的代码示例时,我遇到了8个错误。我正在运行java 7 u51。好像编译器没有认识到oracle教我的lambda表达式的语法。我真的希望这些教程不会过时,因为它们是我发现的第一个能够清楚解释所有内容的教程。

import java.util.function.Consumer;

public class LambdaScopeTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {

            // The following statement causes the compiler to generate
            // the error "local variables referenced from a lambda expression
            // must be final or effectively final" in statement A:
            //
            // x = 99;

            Consumer<Integer> myConsumer = (y) -> 
            {
                System.out.println("x = " + x); // Statement A
                System.out.println("y = " + y);
                System.out.println("this.x = " + this.x);
                System.out.println("LambdaScopeTest.this.x = " +
                    LambdaScopeTest.this.x);
            };

            myConsumer.accept(x);

        }
    }

    public static void main(String... args) {
        LambdaScopeTest st = new LambdaScopeTest();
        LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

错误:

C:\java>javac LambdaScopeTest.java
LambdaScopeTest.java:19: illegal start of expression
            Consumer<Integer> myConsumer = (y) ->
                                                ^
LambdaScopeTest.java:20: illegal start of expression
            {
            ^
LambdaScopeTest.java:28: <identifier> expected
            myConsumer.accept(x);
                             ^
LambdaScopeTest.java:28: <identifier> expected
            myConsumer.accept(x);
                               ^
LambdaScopeTest.java:33: class, interface, or enum expected
    public static void main(String... args) {
                  ^
LambdaScopeTest.java:35: class, interface, or enum expected
        LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
        ^
LambdaScopeTest.java:36: class, interface, or enum expected
        fl.methodInFirstLevel(23);
        ^
LambdaScopeTest.java:37: class, interface, or enum expected
    }
    ^
8 errors

1 个答案:

答案 0 :(得分:2)

Lambda是Java 8.请参阅What's new in Java 8中的java.util.function.Consumer@since