Reputation: 59
I just started going through the language tour for dart and found this piece of code that didn't actually make sense to me could someone please explain this
void main() {
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
}
Also while I was experimenting with this block using print(callbacks)
which just gave me this [Closure 'main_closure', Closure 'main_closure']
Upvotes: 0
Views: 220
Reputation: 71623
It creates a list. It runs through a loop twice, each time creating a function and adding that function to the list. It then runs through the functions in the list and calls each one.
Let's try to rewrite this code for readability rather than brevity:
void main() {
var callbacks = <void Function()>[]; // Create an empty list of functions.
for (var i = 0; i < 2; i++) { // for i being 0 or 1:
void f() { // Create a function f
print(i); // which prints `i` when it's called
}
callbacks.add(f); // Put function f into the callbacks list.
}
for (var c in callbacks) { // For each function c in `callbacks`:
c(); // Call the function c
}
}
This code does effectively the same as the original, only with type checks and less condensed syntax.
The main difference is that the syntax used in the original omits a lot of types (which makes them be dynamic
, so the code has no type checking) and it contains function expressions:
* The expression () => print(i)
is an anonymous function expression. It evaluates to a function value which is equivalent to the one from the named function declaration void f() { print(i); }
, it just doesn't have a name or return type, and it uses =>
for the body, which it can because the body is a single expression.
* The expression (c) => c()
is also an anonymous function expression. It is (in this case) equivalent to a declaration like void callIt(void Function() f) { f(); }
. The List.forEach
expects such a function as argument, and it calls it with each element of the list in turn.
(The point of this example is to show that the i
variable captured during the two loop iterations is a different variable each time through the loop.)
Upvotes: 3