Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking nested functions in the Dart programming language

Tags:

dart

I defined an inner function here:

person(firstName, lastName){
    fullName(){ //Is it possible to invoke this function outside the 'person' function?
        return firstName + " "  + lastName;
    }
    firstInitial(){
        return firstName[0];
    }
    lastInitial(){
        return lastName[0];
    }
}

Next, I tried to invoke the "fullName" function from the "main" function:

void main() {
  print(person("Rob", "Rock").fullName());
}

but it produced this error:

Uncaught TypeError: Cannot read property 'fullName$0' of undefined

Is it possible to invoke an inner function outside the scope where the function is defined?

like image 869
Anderson Green Avatar asked Mar 20 '23 08:03

Anderson Green


1 Answers

You can declare the function outside the enclosing block:

void main() {
  var fullName;
  person(firstName, lastName){
      fullName = () => "firstName: $firstName lastName: $lastName";
  }
  person("Rob", "Rock");
  print(fullName());
}

or return it:

void main() {
  person(firstName, lastName) => () => "firstName: $firstName"
                                       "lastName: $lastName";
  print(person("Rob", "Rock")());
}

If you want this syntax person("Rob", "Rock").fullName() you can return class instance:

class Res{
  var _firstName, _lastName;
  Res(this._firstName, this._lastName);
  fullName() => "firstName: $_firstName lastName: $_lastName";
}
void main() {
  person(firstName, lastName) => new  Res(firstName,lastName);
  print(person("Rob", "Rock").fullName());
}
like image 129
JAre Avatar answered Apr 01 '23 06:04

JAre