Tit*_*lum 6 java lambda java-8
我们能否确定在 java lambda 中调用的方法仅在 lambda 本身执行时调用,而不是提前调用?
如果你看一下我的代码:
StringBuilder myStringBuilder = new StringBuilder("my result");
Supplier<String> mySupplier = () -> "result: " + myStringBuilder.toString();
myStringBuilder.append(", after appending.");
System.out.println(mySupplied.get());
Run Code Online (Sandbox Code Playgroud)
我们能否 100% 确定结果始终是:
结果:我的结果,附加后
并且从来不只是
结果:我的结果
考虑以下片段:
\n\nRunnable runnable = () -> expensiveMethod(); // Runnable not called\nfirstMethodCall(); // Runnable not called\nsecondMethodCall(); // Runnable not called\nrunnable.run(); // HERE IT COMES, Runnable IS called\nRun Code Online (Sandbox Code Playgroud)\n\nlambda 表达式只不过是具有一种方法的匿名类的实现(这可以保证@FunctionalInterface注释的安全性)。
Runnable runnable = new Runnable() {\n void run() {\n expensiveMethod();\n }\n};\n\n// runnable\'s method is not executed since the method run is not called\n// the runnable.run() invokes the expensiveMethod()\nRun Code Online (Sandbox Code Playgroud)\n\nJava 8 规范15.27。Lambda 表达式解释了当调用函数接口的适当方法时调用表达式:
\n\n\n\nlambda 表达式的求值会生成函数接口的实例 (\xc2\xa79.8)。Lambda 表达式求值不会导致表达式主体的执行;相反,这可能会在稍后调用功能接口的适当方法时发生。
\n