This tutorial extends our coverage of functions and explores how Dart functions are first-class objects.
Everything is an Object
Remember how I said everything in Dart is an object. This definition extends to functions as well. Functions are first-class objects. We can pass our functions as arguments to other functions and even assign functions to variables. This flexibility is a very powerful language feature I’m certain you will love.
1. void main(){
2. var listOfStrings = ["functions", 'are', 'objects'];
3. listOfStrings.forEach(saySomething);
}void saySomething(String element) {
print(element);
}
- Entry-point to our app
void main()
- Here we create a list of
String
objects inside the variablelistOfStrings
- For each item within
listOfStrings
—saySomething
is called and the item is passed tosaySomething
as an argument. In more concrete terms, this is what happens:
"functions"
is passed tosaySomething
andsaySomething
prints functions.
"are"
is passed tosaySomthing
andsaySomething
prints are.Finally,
"objects"
is passed tosaySomething
andsaySomething
prints objects.The net effect of passing the function
saySomething
to theforEach
function multiple times can be observed below:
Assigning a Function to a Variable
void main(){
1. var makeTextBig = (String string) => print(string);
2. makeTextBig('make me big'.toUpperCase());}
- We assign an anonymous function to the variable
makeTextBig.
This anonymous function prints a string using shorthand function syntax =>. Anonymous functions are covered below. - We invoke the function through the variable by calling the variable like we would a function and passing it a
String
argument. See output below:
Note how the variable
makeTextBig
is self-documenting. There is no confusion about what this variable does. It makes text — BIG. Having well named variables improves the readability of your code and reduces confusion. Furthermore, it helps declutter your codebase, because you no longer need to comment or annotate your code. Trust me on this one. Everybody who reads your code will be eternally greatful for your dedication to code quality.
Anonymous Functions
Still editing…
Help me help others by clicking on that clap button and leave a response.