Basically I am going through the definition of closure functions which says -
A function that can be referenced with access to the variables in its lexical scope is called a closure
So I want to know this term lexical scope.
Basically I am going through the definition of closure functions which says -
A function that can be referenced with access to the variables in its lexical scope is called a closure
So I want to know this term lexical scope.
lexical scoped variable/closure etc can only be accessed within the block of code in which it is defined.
Dart is a lexically scoped language. With lexical scoping, descendant scopes will access the most recently declared variable of the same name. The innermost scope is searched first, followed by a search outward through other enclosing scopes.
You can “follow the curly braces outwards” to see if a variable is in scope.
See the following example.
main() { //a new scope
String language = "Dart";
void outer() {
//curly bracket opens a child scope with inherited variables
String level = 'one';
String example = "scope";
void inner() { //another child scope with inherited variables
//the next 'level' variable has priority over previous
//named variable in the outer scope with the same named identifier
Map level = {'count': "Two"};
//prints example: scope, level:two
print('example: $example, level: $level');
//inherited from the outermost scope: main
print('What Language: $language');
} //end inner scope
inner();
//prints example: scope, level:one
print('example: $example, level: $level');
} //end outer scope
outer();
} //end main scope
A closure is a function object that has access to variables in its lexical scope, even when the function is used outside of its original scope.
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(num addBy) {
return (num i) => addBy + i;
}
void main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
You can read more from here.
Lexical scope means that where you declare a variable in your code determines where you can use it.
void main() {
int globalVar = 10; // Big box (global scope)
void myFunction() {
int localVar = 5; // Small box (local scope)
print(globalVar); // We can see globalVar here
print(localVar); // We can see localVar here
}
myFunction(); // Runs the function
// print(localVar); // Error! We can't see localVar outside the small box
}
globalVar
is in the big box, so it can be used anywhere in the main
function, including inside myFunction
.localVar
is in the small box, so it can only be used inside myFunction
and not outside of it.Where you put your variables (which box) decides who can use them. If you want everyone to use it, put it in the big box (global scope). If you want only certain parts to use it, put it in a small box (local scope).
© 2022 - 2025 — McMap. All rights reserved.