gpt4 book ai didi

Java 8 Lambda 表达式不起作用

转载 作者:行者123 更新时间:2023-12-01 07:52:20 24 4
gpt4 key购买 nike

我正在尝试以下代码并使用 JDK 1.8.0_66 进行编译。我的代码在语法上似乎是正确的,我错过了什么吗?

interface Executable {
void execute();
}

class Runner {
public void run(Executable e) {
System.out.println("Executing code block!");
e.execute();
}
}

public class HelloWorld {
public static void main(String[] args) {
Runner runner = new Runner();

runner.run(new Executable() {
public void execute() {
System.out.println("IN ANONYMOUS CLASS EXECUTE");
}
});
}

runner.run(() -> System.out.println());

}

抛出以下编译错误:

App.java:25: error: <identifier> expected
runner.run(() -> System.out.println());
^
App.java:25: error: illegal start of type
runner.run(() -> System.out.println());
^
App.java:25: error: ';' expected
runner.run(() -> System.out.println());

最佳答案

您的语句位于定义 runnner 变量的 block 之外。应该是这样的:

public static void main(String[] args) {
Runner runner = new Runner();

runner.run(new Executable() {
public void execute() {
System.out.println("IN ANONYMOUS CLASS EXECUTE");
}
});

runner.run(() -> System.out.println());
}

关于Java 8 Lambda 表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125452/

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