Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 1.49 KB

ex3-5.md

File metadata and controls

46 lines (35 loc) · 1.49 KB

3.5 Declaring Anonymous functions

Example Code:

The code defines two anonymous functions, ex1Squared() and ex1Cubed(). Anonymous functions are functions that do not have a name. They are often used when you need to define a function inline, without having to declare it first.

The ex1Squared() function takes an integer as input and returns the square of that integer. The ex1Cubed() function takes an integer as input and returns the cube of that integer.

The code then calls both anonymous functions twice, once with the value 5 as input. The results of the function calls are printed to the console.

In the first style of anonymous function, the function body is defined using the => operator. In the second style of anonymous function, the function body is defined using curly braces ({}) and the return statement.

void main() {
  int value = 5;

  // Anonymous Function - Style 1
  int ex1Squared(num1) => num1 * num1;
  int ex1Cubed(num1) => num1 * num1 * num1;

  // Anonymous Function - Style 2
  int ex2Squared(num1){ return num1 * num1; }
  int ex2Cubed(num1){ return num1 * num1 * num1; }

  // Anonymous Function - Style 1
  print('EX1: $value squared is ${ex1Squared(value)}');
  print('EX1: $value cubed is ${ex1Cubed(value)}');

  // Anonymous Function - Style 2
  print('EX2: $value squared is ${ex2Squared(value)}');
  print('EX2: $value cubed is ${ex2Cubed(value)}');
}

Example Output:

EX1: 5 squared is 25
EX1: 5 cubed is 125
EX2: 5 squared is 25
EX2: 5 cubed is 125