nus-cs2030 / 2021-s2

2 stars 2 forks source link

Why bar() cannot compile but baz() can? #334

Open Guo-Yujia opened 3 years ago

Guo-Yujia commented 3 years ago

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):

image

gracefour11 commented 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.

Guo-Yujia commented 3 years ago

that's really helpful! Thanks a lot.

chinjuanlee commented 3 years ago

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

lyntan01 commented 3 years ago

Hi, you may also find this link helpful: https://nus-cs2030.github.io/1920-s2/contents/textbook/lecture07/VariableCapture/VariableCapture.html

darrylcjy commented 3 years ago

You can also find this concept in the lecture notes from lecture 9 slide 14

MatthiasTanWeiSheng commented 3 years ago

https://stackoverflow.com/questions/32272713/lambda-expression-and-variable-capture I think this link will be helpful also

JWulaXia commented 3 years ago

thanks! that helps a lot