Dart scope and lexical scoping

Published by admin on

Scope :

Scope is the area that we can access one variable or function. If two variables are under the same scope, one can access another. If they are in different scopes, the program will throw an error.

Curly braces are used to define scope in dart. Anything inside the same curly braces is under the same scope.

Dart is a lexically scoped programming language. It means the current scope is checked first and then other outer scopes are checked. If a variable is under a scope, you can access it.

 

Examples of scope :

Let’s check the below example :

main(List<string> args) {
  foo(){
    print("Hello from foo !");
  }
  foo();
}

This program will work.

The scope starts with the start of the main function. Function foo() is called from the main function i.e. we are calling it from the same scope.

main(List<string> args) {
  fooOuter() {
    print("Hello from foo outer !");

    fooInner() {
      print("Hello from foo !");
      fooOuter();
    }
  }

  fooOuter();
  fooInner();
}

 

In this example, fooInner can call fooOuter because fooInner is in the scope of fooOuter. Similarly, from the main’s scope, we can call fooOuter.

We can’t call fooInner() from main. The compiler will show one error like below :

Dart lexical scoping

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *