Chapter 4. Functional first-class functions and closures
This chapter covers
- Declaring functions and return types
- Specifying mandatory and optional parameters
- Storing first-class functions in variables
- Using functions as closures
Dart is similar in many ways to languages such as Java and C#, but its function syntax is more similar to that found in JavaScript than in more strongly typed languages. In Dart, everything is an object, including functions, which means you can store a function in a variable and pass it around your application the same way that you might pass a String, an int, or any other object. This is known as having first-class functions, because they’re treated as equivalent to other types and aren’t second-class citizens in the language.
First, we’ll examine Dart’s function syntax options, which have a longhand and a shorthand notation and various forms, depending on how much optional type information you provide. You’ll take these functions and use them as variables and pass functions around as parameters and return types.
Once you have a grounding in using functions as first-class objects by storing them in variables, we’ll look at how you can define function types to provide strong type information. These definitions help the type system validate that functions you’re passing around your application match the developers’ intentions.