Closures & Scope In Dart

Closures & Scope In Dart

·

1 min read

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.

  • Functions can close over variables defined in surrounding scopes. In the following example, makeAdder() captures the variable addBy. Wherever the returned function goes, it remembers addBy.

    dart

  •   /// Returns a function that adds [addBy] to the
      /// function's argument.
      Function makeAdder(int addBy) {
        return (int 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);
      }
    

Lexical Scope

  • Dart is a lexically scoped language, which means that the scope of variables is determined statically, simply by the layout of the code. You can "follow the curly braces outwards" to see if a variable is in scope.

  •   bool topLevel = true;
    
      void main() {
        var insideMain = true;
    
        void myFunction() {
          var insideFunction = true;
    
          void nestedFunction() {
            var insideNestedFunction = true;
    
            assert(topLevel);
            assert(insideMain);
            assert(insideFunction);
            assert(insideNestedFunction);
          }
        }
      }