我正在尝试阅读此内容 https://leanpub.com/whatsnewinjava8/read#leanpub-auto-scope我有点困惑:
- 为什么在 r1 的赋值中调用 toString()
- 这如何演示 lambda 可用的范围
最佳答案
我可以肯定地回答第一个问题:
当您调用函数System.out.println
时,它将执行以下操作:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
来源:https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#println-java.lang.Object-
随后调用String.valueOf(x)
将执行以下操作:
If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
来源: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#valueOf-java.lang.Object-
由于 this
引用 Hello
的实例,因此它只会在给定实例上调用 Hello.toString()
方法 - 调用堆栈:
System.out.println(this);
String.valueOf(this);
this.toString();
关于范围的第二个问题可能意味着您仍然可以引用封闭类的方法和字段,但我发现这个示例很奇怪,而且文档也没有很好地记录。
关于来自 Leanpub 的 Java 8 lambda 范围示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60679204/