![]() Every call to get_plus(), returns a copy of plus, packaged together with a value for increase. These can be considered the two parameters to plus, one from the parameter list, the other from the surrounding scope. The plus function adds two numbers, start and increase. Closures as code, packaged with Parameters Thus add8 is add6 returns False, and the two closures returned are not the same. A different closure, where a closure is the combination of function and environment the function can access. Even though the code is the same, the environment is different for each plus, so the two calls do return something different. Also get_plus(8) would return a copy of plus where increase in the environment is 8. So get_plus(6) returns a copy of plus where increase in the environment is 6. This ‘code’ + environment is what is called a closure. The ‘plus’ returned by get_plus, is actually not just ‘plus’ but plus together with the stack frame, or local environment of get_plus, at the time plus is returned. In this case, the only local data is the parameter ‘increase’, but there could be any number of local variables and parameters… anything in the scope of get_plus is part of the environment of get_plus. This stackframe will hold the parameters for get_plus together with any local variables of get_plus. When a program calls get_plus, at runtime a ‘stackframe’ is created for the get_plus function. ![]() It (get_plus) does not call plus(), but just returns the function plus without calling the code in plus. The function get_plus returns the plus function. Lets start with an example, and then discuss how it works. class level methods/companion object methods.Closures as code, packaged with parameters.Everything you ever wondered about closures, and a few things more:
0 Comments
Leave a Reply. |