0
我一直在使用docs.oracle.com作爲學習java的方式,當我試圖編譯下面的代碼示例時,出現了8個錯誤。我正在運行Java 7 u51。好像編譯器沒有認識到oracle教給我的lambda表達式的語法。我真的希望這些教程不會過時,因爲它們是我發現的第一個清楚解釋所有內容的教程。docs.oracle.com 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
這是它的感謝! –