nus-cs2030 / 2021-s1

27 stars 48 forks source link

Lexical Scoping #218

Open shawnkai opened 4 years ago

shawnkai commented 4 years ago

Description

Hi guys I'm still quite unsure of this lexical scoping thing with regards to the use of lambda. Can anyone help me out and explain it in a simple way if possible. Apart from that, how does using lambda benefit me with regards to lexical scoping vs if I didn't use lambda. Thank you in advance!

Topic:

Lexical Scoping

Screenshots (if any):

Insert Images here if necessary

Terence-Sim commented 4 years ago

Let's use a simple lambda as example: (x,y) -> x+y+z + foo();

This lambda has 2 parameters: x,y. In the body, the lambda has 2 free variables (variables not in the parameter list): z and foo. Lexical scoping means that the free variables (in this case, z and foo) will refer to variables in the enclosing scope where the lambda was created.

You cannot avoid lexical scoping in Java. It is the rule specifying where free variables should be looked up to get their actual values.