Dart Anonymous Functions: Higher-Order Functions with Collections
Table of contents
An anonymous function in Dart is like named function but they do noy have names associated with it.
An anonymous function can have zero or more parameters with optional type annotations.
In dart most of the functions are named functions we can also create nameless function knows as an anonymous function, lambda, or closure.
In dart we can assign any anonymous function to constants or variables, later we can access or retrieve the value of closure based on our requirements.
High Order Function:
When a function returns another function ,it is referred to as a High Order Function, or When a function takes parameter as a function, it is called a higher-order function.
In this example, we are using a lambda function to demonstrate how a higher-order function works.
In
main()
, we define a lambda functionaddTwoNumbers
using the syntax(int a, int b) => a + b
. This function takes two integers as input parametersa
andb
, and it returns their sum.addTwoNumbers
is then passed as an argument to the higher-order functionmyNewFunction
.The
myNewFunction
function takes a stringmsg
and a functionsummation
as parameters. It prints the messagemsg
and then calls thesummation
function with6
and7
as arguments, printing the result.This demonstrates the use of lambda functions (anonymous functions) and higher-order functions in Dart. Lambda functions are convenient for short, simple functions, and higher-order functions allow for functions to be passed around as arguments or returned from other functions.
Subscribe to my newsletter
Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by