Lexical Scope and Closure
Lexical Scope :
Lexical scope is a very important term in any programming language. It defines the scope of the variable based on the block it is contained inside. According to the lexical scope, the scope of the variable does not exist when the control is out of the block in which the variable was present. Dart is a lexically scoped language; therefore, we can find the scope of the variable by tracing the curly braces.
Consider the following example that explains the concept of lexical scope.
// Declaring a global variable whose scope is the whole program
// Therefore, this variable can be used anywhere in the program in any
// function
var global = 5 ;
void main( )
{
// Declaring a local variable inside main( ). This variable can be
// accessed only within this function
var inside_main = 6 ;
print( " Value of global variable is : $global " ) ;
print( " Value of variable inside main( ) is : $inside_main " ) ;
void func_1( )
{
// Declaring a local variable inside func_1( ). This variable can be
// accessed only within this function
var inside_geeksforgeeks = 7 ;
void func_2( )
{
// Declaring a local variable inside func_2( ). This variable can be
// accessed only within this function
var inside_geek = 8 ;
}
}
}
Output :
Value of global variable is : 5
Value of variable inside main( ) is : 6
The above code explains the concept of the scope of the variable inside the functions in a program and how their scope ends outside the curly braces.
Lexical Closures :
In programming languages, lexical scope of a variable in a function can be implemented using lexical closure also called the closure or function closure. The implementation includes a function object that has access to variables in its lexical scope, even when the function is used outside the scope.
Consider the following example that explains the concept of lexical closure :
Program :
// definition of the function that adds the number
Function func1( num add )
{
return ( num i ) => add + i ;
}
void main( )
{
// creating an object ' obj1' that calls the func1( ) function to add 5
var obj1 = func1( 5 ) ;
// creating an object ' obj1' that calls the func1( ) function to add 5
var obj2 = func1( 10 ) ;
// passing the values in the object
// printing the value of obj1 after adding 1 and 5
print( " Value of first object : " ) ;
print( obj1( 1 ) ) ;
// printing the value of obj1 after adding 1 and 10
print( " Value of Second object : " ) ;
print( obj2( 1 ) ) ;
}
Output :
Value of first object :
6
Value of Second object :
11