Sobes.tech
Junior

What is the difference between anonymous functions and regular functions?

sobes.tech AI

Answer from AI

Anonymous functions are functions without a name. They are often used for one-time calls or as callbacks.

Main differences:

  • Name: Regular functions have a name and can be called by it. Anonymous functions do not have a name.
  • Definition: Regular functions are defined using the func keyword (or equivalent in other languages) followed by a name, parameters, and a body. Anonymous functions are defined "on the fly," often at the point of use.
  • Passing: Anonymous functions are often passed as arguments to other functions (e.g., in map, where, forEach methods). Regular functions can also be passed, but they are more often used to define logic called by name.
  • Scope: Anonymous functions have access to variables from the scope where they were defined (closure "capture" effect). Regular functions usually have their own scope.

Example in Dart/Flutter:

Regular function:

void greet(String name) {
  print('Hello, $name!');
}

// Calling the regular function
greet('World');

Anonymous function (lambda):

// Using an anonymous function in list iteration
List<int> numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) {
  print(number * 2); // Anonymous function performing multiplication
});

// Anonymous function assigned to a variable
var multiplyByTwo = (int number) => number * 2;
print(multiplyByTwo(5));