Open Guo-Yujia opened 3 years ago
You can refer to the statement below from this link
Lambda expressions can use variables defined in an outer scope. We refer to these lambdas as capturing lambdas. They can capture static variables, instance variables, and local variables, but only local variables must be final or effectively final.
In this case, x
is the local variable in the Runnable bar()
function, and x = x + 1
doesn't make x
effectively final or final. So it cant compile.
that's really helpful! Thanks a lot.
Hi, this is due to variable capture. Local variables must be final or effectively final (as replied earlier). For static variables, instance variables (as defined in the attributes), these variables may not be final so baz() can mutate the static int y variable! Hope this helps
Hi, you may also find this link helpful: https://nus-cs2030.github.io/1920-s2/contents/textbook/lecture07/VariableCapture/VariableCapture.html
You can also find this concept in the lecture notes from lecture 9 slide 14
https://stackoverflow.com/questions/32272713/lambda-expression-and-variable-capture I think this link will be helpful also
thanks! that helps a lot
Summary
For this question, I don't really understand why it compiles for baz() and does not compile for bar(). What's the reason behind it?
Description
Post the question that you would like your peers or seniors to answer.
Suggested Answer (if any):
Post your answer or the suggested answer, if any.
Screenshots (if any):