Ad

What Is The Lexical Scope In Dart?

- 1 answer

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.

Ad

Answer

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.

Here is an example of nested functions with variables at each scope level:

String topLevel = 'Hello';

void firstFunction() {
  String secondLevel = 'Hi';
  print(topLevel);
  nestedFunction() {
    String thirdLevel = 'Howdy';
    print(topLevel);
    print(secondLevel);
    innerNestedFunction() {
      print(topLevel);
      print(secondLevel);
      print(thirdLevel);
    }
  }
  print(thirdLeve);
}

void main() => firstFunction();

This is a valid function, until the last print statement. The third-level variable is defined outside the scope of the nested function, because scope is limited to its own block or the blocks above it.

Ad
source: stackoverflow.com
Ad