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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With