flutterdartclosureslexical-scope

What is the Lexical Scope in dart?


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.


Solution

  • 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
    

    Lexical closures

    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.