nus-cs2030 / 2021-s2

2 stars 2 forks source link

Lambda Capturing #340

Open JoelToh404 opened 3 years ago

JoelToh404 commented 3 years ago

Summary

Hi sorry if its a stupid question but is lambda capturing and closures tested? There is only one mention of it in the lecture slides and it is quite difficult to grasp the concept from there. Thanks!!!

ShyamalSankar commented 3 years ago

Im not sure but heres a link that gives a decent explanation! https://www.baeldung.com/java-lambda-effectively-final-local-variables

hewtungyuen commented 3 years ago

if im not wrong, we cannot modify a local variable (within the same method) with a stream

clementyee303 commented 3 years ago

if im not wrong, we cannot modify a local variable (within the same method) with a stream

The reason for that is because the lambda would make a deep copy of the referenced local variables (because it cannot guarantee that the local variables would always be available), Hence, modifying the local variables in the same method (after the lambda is created) would not change the local variable that was supposedly referenced in the lambda (even though you would expect that to be the case). Thus, the java compiler simply requires local variables to be effectively final to avoid any misunderstandings.

Note that the instance and static variables do not have to be effectively final, as they are guaranteed to exist along with the lambda method (given that the instance variable is of the same class)