воскресенье, 4 апреля 2021 г.

Closures

//Anonymous functions
void main() {

  //around scope
  var b = 3; // closure can use it

  //Anonymous functions - Closure or Lambda
  Function emptyFn = (){}; //empty function
  Function aFn = (int a) => print(a * b); //void (int) - action
  //void Function(int) aFn = (int a) => print(a * b);
  void nFn(Function aFn) => aFn(5); //function as parameter
  aFn(5); //() - function operator
  nFn(aFn);

  Function nFn1() { return () => print('return function'); };
  (nFn1())(); // call function from function

  final hi = (String name) => 'Hi, $name'; //String (String)
  print(hi('Sam'));

  //Functions as first class objects
  welcome(hi, 'Patric1');
  welcome((String name) => 'Hi, $name', 'Patric2');

  //Function types
  String bon(String name) => 'Bon, $name';
  String hola(String name) => 'Hola, $name';
  welcome1(hi, 'Patric3');
  welcome1(bon, 'Patric4');
  welcome1(hola, 'Patric5');

  //Closures and collections
  const multiplier = 10;
  const list1 = [1, 2, 3];
  // one expression - =>
  final result = list1.map((e) => e * multiplier);
  // more than one expression - {}
  final result1 = list1.map((e) {
    e++;
    return e * multiplier;
  });

  print(result);
  print(result1);

}

//Functions as first class objects
void welcome(String Function(String) greet, String name) {
  print(greet(name) + ', Welcome!');
}

//Function types
typedef Greet = String Function(String);
//or
//typedef String Greet(String name);

void welcome1(Greet greet, String name) {
  print(greet(name) + ', Welcome!');
}

Комментариев нет:

Отправить комментарий