David Stutz
David Stutz

Reputation: 2618

Assign function/method to variable in Dart

Does Dart support the concept of variable functions/methods? So to call a method by its name stored in a variable.

For example in PHP this can be done not only for methods:

// With functions...
function foo()
{
    echo 'Running foo...';
}

$function = 'foo';
$function();

// With classes...
public static function factory($view)
{
    $class = 'View_' . ucfirst($view);
    return new $class();
}

I did not found it in the language tour or API. Are others ways to do something like this?

Upvotes: 17

Views: 28807

Answers (2)

Divyanshu Kumar
Divyanshu Kumar

Reputation: 1451

I may not be the best explainer but you may consider this example to have a wider scope of the assigning functions to a variable and also using a closure function as a parameter of a function.

  void main() {
      // a closure function assigned to a variable.
      var fun = (int) => (int * 2); 
      // a variable which is assigned with the function which is written below
      var newFuncResult = newFunc(9, fun); 
      print(x); // Output: 27
    }

    //Below is a function with two parameter (1st one as int) (2nd as a closure function)
        int newFunc(int a, fun) {
          int x = a;
          int y = fun(x);
          return x + y;
        }

Upvotes: 1

Lars Tackmann
Lars Tackmann

Reputation: 20865

To store the name of a function in variable and call it later you will have to wait until reflection arrives in Dart (or get creative with noSuchMethod). You can however store functions directly in variables like in JavaScript

main() {
  var f = (String s) => print(s);
  f("hello world");
}

and even inline them, which come in handy if you are doing recusion:

main() {
   g(int i) {
      if(i > 0) {
         print("$i is larger than zero");
         g(i-1);
      } else {
         print("zero or negative");
      } 
   }
   g(10);
}

The functions stored can then be passed around to other functions

main() {
   var function;
   function = (String s) => print(s);
   doWork(function);
}

doWork(f(String s)) {
   f("hello world");
}

Upvotes: 20

Related Questions