Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as an argument in another function - Dart

What's the difference between

void test1(void fun(String element)) {
  fun("Test1");
}

//AND

void test2(Function(String element) fun) {
  fun("Test2");
}

I tried to run both of them and can't find any differences in the output:

void main() {
  test1((test) => print(test));
  test2((test) => print(test));
}

void test1(void fun(String element)) {
  fun("Test1");
}

void test2(Function(String element) fun) {
  fun("Test2");
}

// Output:  
// Test1   
// Test2

I'm new to Dart I've always been using Java, so passing function to a function is something new to me, so if someone can explain to me what's the differences in the above code would be very grateful.

like image 738
Yousef Gamal Avatar asked Oct 24 '18 06:10

Yousef Gamal


People also ask

Can you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.

What function passes an argument to another function?

When they're passed as an argument to another function, they're known as a 'callback' — to be called when the other function is ready for them. Common examples of callbacks include functions provided to: forEach or map to be called on each item in a collection.


1 Answers

There is no real difference between declaring a function parameter with a function type preceding the name (void Function(String) fun), or as a (C-like) function-like syntax where the name is in the middle (void fun(String element)). Both declare an argument named fun with type void Function(String).

Dart didn't originally have a way to write a function type in-line, you had to use a typedef, so most older code uses the void fun(String element) notation. When the returnType Function(arguments) notation was introduced (because it was needed for specifying generic function types), it became easier to write function typed parameters with the type first.

Both are being used, neither is idiomatic, use whatever you think reads best.

There is one difference between the two formats that are worth remembering:

  • The void fun(String element) notation requires names for the function arguments. If you write void fun(String) it is interpreted as a function taking one argument of type dynamic with the name String.
  • The void Function(String) fun notation assumes that a single argument name is the type.

I personally prefer the original function parameter format, except for having to write the argument names.

like image 172
lrn Avatar answered Sep 28 '22 20:09

lrn