Consider the following almost compilable Java 8 code:
public static void main(String[] args) {
LinkedList<User> users = null;
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
User user = users.stream().filter((user) -> user.getId() == 1).findAny().get();
}
static class User {
int id;
String username;
public User() {
}
public User(int id, String username) {
this.id = id;
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public int getId() {
return id;
}
}
You'll notice User user = users.stream().filter((user) -> user.getId() == 1).findAny().get();
throws a compiler error:
variable user is already defined in method main(String[])
My question is: Why do Lambda expressions consider the variable that is being initialized on the same line as the Lambda expression as already defined? I understand Lambdas look outside themselves for (and use) local variables, so you can't name the variables you use inside the Lambda the same as an outside variable. But why is the variable that is being defined considered already defined?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…