我们能否确定在 java lambda 中调用的方法仅在 lambda 本身执行时才被调用,而不是提前被调用?
如果你看看我的代码:
StringBuilder myStringBuilder = new StringBuilder("my result");
Supplier<String> mySupplier = () -> "result: " + myStringBuilder.toString();
myStringBuilder.append(", after appending.");
System.out.println(mySupplied.get());
我们能否 100% 确定结果将永远是:
result: my result, after appending
永远不要只是
result: my result
最佳答案
考虑以下快照:
Runnable runnable = () -> expensiveMethod(); // Runnable not called
firstMethodCall(); // Runnable not called
secondMethodCall(); // Runnable not called
runnable.run(); // HERE IT COMES, Runnable IS called
lambda 表达式只不过是使用一种方法实现匿名类(这确保了
@FunctionalInterface
注释)。Runnable runnable = new Runnable() {
void run() {
expensiveMethod();
}
};
// runnable's method is not executed since the method run is not called
// the runnable.run() invokes the expensiveMethod()
Java 8 规范 15.27. Lambda Expressions解释当调用函数接口(interface)的适当方法时调用表达式:
Evaluation of a lambda expression produces an instance of a functional interface (§9.8). Lambda expression evaluation does not cause the execution of the expression's body; instead, this may occur at a later time when an appropriate method of the functional interface is invoked.
关于java - lambda 中的方法是否仅在执行 lambda 时才被评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876934/