Jpaji Rajnish
Jpaji Rajnish

Reputation: 1501

docs.oracle.com lambda expression example won't compile

I've been using docs.oracle.com as my way to learn java and when I tried to compile this code example below, I got 8 errors. I'm running java 7 u51. It seems like the compiler isn't recognizing the syntax of lambda expressions that oracle is teaching me. I really hope these tutorials aren't outdated because they're the first ones I've found that explain everything clearly.

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);
    }
}

And the errors:

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

Upvotes: 0

Views: 239

Answers (1)

steffen
steffen

Reputation: 17038

Lambda is Java 8. See What's new in Java 8 and @since in java.util.function.Consumer.

Upvotes: 2

Related Questions