Dart contains a cool feature that you can find in other languages - that is, you put a function inside of another function?
Now why would you want to do this? Well, let’s say you were writing a filtering function. Yet the source data is encoded, so you need another function to decode the data. Now that function isn’t used anywhere else in your program so it makes sense to nest it in that function.
Now sometimes, your functions will return another function. This gets interesting when we return our nested function. This returned nested function is called a closure because the returned function encapsulates -
or closes over - all the variables in the parent function. This means, the function has state.
Yes, that sound weird, but its a great way to keep track of internal state and like variables, can be passed around the function. Let’s play around with some closures.
To get started, open DartPad.dev. We’re going to create a function called apply multiplier. We will pass in a multiplier to the that we can use to multiply other numbers.
First let’s define the function taking in a multiplier.
Function applyMultiplier(num multiplier) {
}
This multiplier number is passed into the body of the function. Now let’s have it return a closer.
return (num value) {
return value * multiplier;
};
Our closure takes in a value which is multiplies by our multiplier. You see, the closure captures the multiplier value. Now lets create a series of different closures.
var doubleMultiplier = applyMultiplier(2);
var tripleMultiplier = applyMultiplier(3);
var quadMultiplier = applyMultiplier(4);
Now lets call our multiplies on the number ten.
print(doubleMultiplier(10));
print(tripleMultiplier(10));
print(quadMultiplier(10));
Now run the program. We get all our modifiers. Notice that each closure maintains its own state. This is just scratching the surface of object oriented programing which is covered in the next course. But before you do anything with objects, you first need to have an understanding of generics which is coming up next.