我理解为什么编译器不接受以下内容:
class Foo {
public Supplier<String> makeSupplier() {
String str = "hello";
Supplier<String> supp = () -> return str;
// gives the expected compile error because
// str is not effectively final
// (str is a local variable, compile-time error
// as per JLS 15.27.2.)
str = "world";
return supp;
}
}
Run Code Online (Sandbox Code Playgroud)
令我困惑的是编译器接受以下内容,并且单元测试通过:
class Bar {
private String str = "hello";
public void setStr(String str) {
this.str = str;
}
public Supplier<String> makeSupplier() {
Supplier<String> supp = () -> { …Run Code Online (Sandbox Code Playgroud)