Skip to content

Instantly share code, notes, and snippets.

@manderly
Created February 21, 2020 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manderly/6f75506652aca65728f3fe91ebf42bce to your computer and use it in GitHub Desktop.
Save manderly/6f75506652aca65728f3fe91ebf42bce to your computer and use it in GitHub Desktop.
// Closure example, sort of a companion to my JS example:
// https://repl.it/@MandiGrant/JSClosureExample
// combineNames is a function that returns a function.
var combineNames = (firstName) {
return (lastName) => firstName + ' ' + lastName;
};
/* If you call it like this,
* combineNames(Jake);
*
* You'll get a function back and you can set it or call it right away. I find it helpful to imagine the function as it might look if it were written as a standalone function, like this. Imagine you get this whole thing back:
*
* var foo(lastName) {
return Jake + ' ' + lastName
};
* You'll notice the firstName you gave it sorta got baked in and now you can call it with a lastName */
void main() {
var returnedFunction = combineNames('Jake');
// combineNames returned a function, you can verify that by printing it.
print(returnedFunction);
var fullName = returnedFunction('Example');
print(fullName);
// Now the full name is there.
}
/* This is what is meant when it is said that returnedFunction has "closure" over firstName.
A closure can also be said to be the combination of the environment a function was declared in and what's in scope around it. When you declared the inner function (the first call to combineNames), you create a closure with the data it has access to (firstName, in this case), which is called its "lexical scope". Things in the lexical scope are really just what it has access to, like in the block scope or class scope. I hope this helps - I tried to come up with the absolute simplest example of closure that I could.
Note: Sorry about the underlining, it appears to be a known issue with Dart and block functions. I wanted to expand it out like this so it's more readable. It still works as intended.
*
* You could write combineNames like this instead:
*
* var combineNames = (firstName) => (lastName) => firstName + ' ' + lastName;
*
* But I thought that might add some unnecessary complexity to this demo.
Issue ticket: https://github.com/dart-lang/sdk/issues/34503
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment