How Dart interprets a ()=>{x,y,z} Arrow in lambda/anonymous functions

Asked

Viewed 232 times

0

Have a similar question here (referring to javascript) but I believe that there are different characteristics in the implementation with Dart.

Example in Dart:

void main() { 
  printName(() => { //ex:1
        print('nome1'),
        print('nome2'),
      });

  printName(() { //ex:2
    print('nome3');
    print('nome4');
  });
}

printName(Function printNames) {
  printNames();
}

In the first example the expression lambda com arrow function the commands are 'delimited' by comma, the compiler interprets the two in the same way or has some difference?

1 answer

3


That’s because in Dart, big arrow function always denotes a return.

Unlike Javascript, in Dart, when you open keys after the arrow (=>) of big arrow function, you’re not opening a scope, you’re opening a Map or a Set.

That is, with the following function:

printName(() => { //ex:1
    print('nome1'),
    print('nome2'),
});

You are declaring a Set which will have the values returned by the functions print('nome1') and print('nome2'), which should not be possible, because the function print is void, no return. As in Dart, inside a Set values are separated by comma, syntax requires a comma, not point and comma between values.

So, since the Dart question has been compared to Javascript, here is the function equivalence:

Equivalent functions (no return):

// Dart
arr.forEach((x) {
    print(x);
});

// JavaScript
arr.forEach((x) => {
    console.log(x);
});

Equivalent functions (return a Map/Object):

// Dart
arr.map((x) => { "val": x });

// JavaScript
arr.map((x) => ({ "val": x }));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.