Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign function/method to variable in Dart

Tags:

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?

like image 755
David Stutz Avatar asked Apr 24 '12 20:04

David Stutz


People also ask

How do you assign a function to a variable in darts?

Dart function simple exampleint z = add(x, y); We call the add function; it takes two parameters. The computed value is passed to the z variable. The definition of the add function starts with its return value type.

Can you pass functions as parameters in Dart?

You can pass around functions in Dart as objects, in a manner similar to in JavaScript: you can pass a function as a parameter, store a function in a variable, and have anonymous (unnamed) functions to use as callbacks.

How do you define a method in darts?

A Dart method is the collection of statements that consists of some characteristics to class object. It provides the facility to perform some operation and it can be invoked by using its name when we need in the program. Methods divide the large task into small chunks and perform the specific operation of that program.


1 Answers

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");
}
like image 188
Lars Tackmann Avatar answered Oct 15 '22 05:10

Lars Tackmann