gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:40:36 25 4
gpt4 key购买 nike

我一直使用 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

最佳答案

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

关于java - docs.oracle.com lambda 表达式示例无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24555558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com