Dart Higher Order Functions
Higher-Order Functions in Dart
A higher-order function is a function that can:
- Take one or more functions as arguments, or
- Return a function as its result.
Higher-order functions are a powerful concept in functional programming, and Dart supports them seamlessly. These functions allow you to write more reusable and flexible code.
Higher-Order Function Example: Passing Functions as Arguments
In Dart, you can pass a function as an argument to another function. Let’s see an example:
Output:
In this example:
performOperation
is a higher-order function because it takes a function (operation
) as an argument.- We pass
add
andmultiply
functions toperformOperation
, and it uses them to perform the corresponding operations on the given numbers.
Higher-Order Function Example: Returning Functions
In addition to accepting functions as arguments, Dart allows functions to return other functions. Here's an example:
Output:
In this example:
makeMultiplier
is a higher-order function because it returns a function (a closure).multiplyBy2
andmultiplyBy3
are functions that "remember" the multiplier value they were created with and use it when called.
Higher-Order Functions with Anonymous Functions
You can also pass anonymous functions (also called lambdas or arrow functions) as arguments to higher-order functions. This is a common pattern in Dart, especially in callbacks and asynchronous programming.
Output:
In this example:
processList
is a higher-order function that accepts a list of numbers and a function (operation
).- We pass an anonymous function that multiplies each number by 2, demonstrating how higher-order functions can be used with inline functions.
Using Built-In Higher-Order Functions
Dart also provides built-in higher-order functions, particularly for collections. For example, you can use map()
, reduce()
, forEach()
, and other functions that take callbacks or return new functions.
Example with map()
:
Output:
In this example:
map()
is a higher-order function that takes a function ((number) => number * 2
) as an argument and applies it to each element in the list.- It returns a new iterable (converted to a list using
toList()
), which is the result of applying the function to each element.
Summary of Higher-Order Functions in Dart
- Passing Functions as Arguments: A higher-order function can accept a function as a parameter.
- Returning Functions: A higher-order function can return a function.
- Anonymous Functions: Dart allows you to pass anonymous functions as arguments, providing more flexibility.
- Built-in Higher-Order Functions: Dart provides many built-in higher-order functions like
map()
,reduce()
,forEach()
, etc., to operate on collections.
Higher-order functions help in writing more modular, flexible, and reusable code by allowing functions to act as first-class citizens, just like variables.