Search code examples
functionvariablesdartfunction-declaration

Dart - declare function as variable


In Dart - as in many other languages - there is more than one way to declare a function. The question is, are there any differences aka "when should I use which"?

void foo(int i) {
  print('i = $i');
}

void main() {
  void Function(int) bar = (int j) {
    print('j = $j');
  };

  foo(1);
  bar(2);
}

Is there any difference in the declaration of foo or bar other than the fact that bar can be overwritten?


Solution

  • Functions can be introduced by

    • function declarations
    • method decla-rations
    • getter declarations
    • setter declarations
    • constructor declarations
    • function literals

    In terms of Dart specification there is 2 differences between function literals (aka anonymous function) and other declarations

    1. it has no name - anonymous
    2. we can't declare a return type (which only obtained by means of type inference)

    If you prefer to keep type safety, you will have to write long declaration.

    Consider this example:

    String foo(int i, {bool b}) => '$b $i'; // return type declared
    
    final bar = (int i, {bool b}) => '$b $i'; // return type could not be infered
    
    final String Function(int i, {bool b}) bar = (i, {b}) => '$b $i'; // return type infered
    

    From my perspective

    1. bar isn't as readable as foo declaration
    2. Let functions literals do their anonymous job =)

    PS If I missed anything - please edit my answer or reach me in comments