Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach() iteration without defining method

Tags:

dart

Sorry about the confusing title, but i don't really know how to summarize this question.

Classes inheriting Iterable in Dart have a forEach() method. While they are nice and easy to use, I'm often in the situation where I'd like to do a small number of operations with the value, without the need to define a method for it, to improve the code's readability. Like PHP's foreach syntax, for example. So instead of writing:

void main() {  
  List<int> l = [1, 2, 3];
  l.forEach(doSomethingWithValue);
}

void doSomethingWithValue(int val) {
  String str = getStringFor(val);
  print(str);
}

I'd like to write something like this:

l.forEach((val) => {
  String str = getStringFor(val);
  print(str);
});

Of course, this code doesn't work, but I hope it demonstrates what I want to do. Is there any way to accomplish this?

like image 234
MarioP Avatar asked Dec 12 '22 15:12

MarioP


1 Answers

You're actually extremely close; you just need to get rid of the =>. That's the syntax for a single-expression function body. To define a function with multiple statements in the body, grouped within brackets, the bracketed body follows the parenthesized parameter list without => in between:

l.forEach((val) {
  String str = getStringFor(val);
  print(str);
});

Note that this concept applies to named functions as well as to anonymous functions as in your example.

void doSomethingWithValue(int val) => print(val);

is the same as

void doSomethingWithValue(int val) {
  print(val);
}

Also note that a function body of the => form returns the value of its expression:

int tripleValue(int val) => val * 3;

is the same as

int tripleValue(int val) {
  return val * 3;
}
like image 181
Darshan Rivka Whittle Avatar answered Jan 27 '23 16:01

Darshan Rivka Whittle