On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. A Function Is a Value
  4. 2. Parameters Work as Usual
  5. 3. Function Types
  6. 4. The Lambdas You've Already Met
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 039: Lambdas

Day14: Lambdas, Higher-Order Functions & Closures
Lecture039 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

Since Day 5 you've been writing little things like (n) => n > 10 inside where. Those are lambdas: functions without a name, written right where they're needed. This lecture explains them properly, so they stop being magic.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 025–027 (functions and parameters) and 013 (where).


Learning Objectives

  • Understand that in Dart a function is a value
  • Write a lambda in block form and in arrow form
  • Store a lambda in a variable and call it
  • Give a variable a function type like int Function(int)
  • Read the lambdas you've already used with where, sort and map

1. A Function Is a Value

In Dart, a function can be stored in a variable, just like a number or a string. A lambda (also called an anonymous function) is a function written without a name:

dart
int square(int n) {           // a normal, named function
  return n * n;
}

var squareLambda = (int n) {  // a lambda in a variable
  return n * n;
};

var squareArrow = (int n) => n * n;   // the same, in arrow form

print(square(5));        // 25
print(squareLambda(5));  // 25
print(squareArrow(5));   // 25

The shape is (parameters) { body } or (parameters) => expression. Note the ; after the lambda: it ends the var statement.

2. Parameters Work as Usual

dart
var greet = () => 'Hello!';
print(greet());   // Hello!

var add = (int a, int b) => a + b;
print(add(2, 3)); // 5

var describe = (String name, {int age = 0}) => '$name ($age)';
print(describe('Ali', age: 20));   // Ali (20)

3. Function Types

A lambda has a type that describes its parameters and result. Write it with Function:

dart
int Function(int) triple = (n) => n * 3;
print(triple(4));                  // 12
print(squareArrow.runtimeType);    // (int) => int

int Function(int) means "a function that takes an int and returns an int". With the type written, the lambda's parameter types can be left out: (n) => n * 3.

4. The Lambdas You've Already Met

dart
var numbers = [3, 8, 1];
numbers.sort((a, b) => a - b);                 // how to compare two items
print(numbers);                                // [1, 3, 8]
print(numbers.map((n) => n * 10).toList());    // how to change each item
// [10, 30, 80]

Each method calls your lambda for you: sort with pairs of items, map and where with each item. That idea, functions that take functions, is the next lecture.


Code Examples

Example 1: Small Text Tools

dart
void main() {
  var toUpper = (String s) => s.toUpperCase();
  var initials = (String full) {
    var parts = full.split(' ');
    return parts.map((p) => p[0]).join();
  };
  var isLong = (String s) => s.length > 10;

  var names = ['ayesha khan', 'bilal ahmed', 'zara'];
  for (var n in names) {
    print('${toUpper(n)} | initials: ${initials(n).toUpperCase()} | long: ${isLong(n)}');
  }
}

Output

code
AYESHA KHAN | initials: AK | long: true
BILAL AHMED | initials: BA | long: true
ZARA | initials: Z | long: false

initials is a block-form lambda (several lines), and it uses another lambda inside map.


Common Beginner Mistakes

1. Printing the lambda instead of calling it

dart
var greet = () => 'Hi';
print(greet);

Output

code
Closure: () => String

That's the function itself. Call it: print(greet());.

2. Wrong argument types

dart
var add = (int a, int b) => a + b;
print(add(1, 'x'));
code
Error: The argument type 'String' can't be assigned to the parameter type 'int'.

Lambdas check their arguments just like named functions.

3. Forgetting the ; after a block lambda: var f = (int n) { return n; } needs a ; after the } because it's a var statement.


Practice Questions

  1. Write a lambda isEven that returns whether an int is even.
  2. Rewrite (int x) { return x - 1; } in arrow form.
  3. What does int Function(String) describe?
  4. What's printed by var f = () => 5; print(f);? And by print(f());?
  5. In list.where((n) => n > 3), what is (n) => n > 3?

Practice Answers

  1. var isEven = (int n) => n % 2 == 0;
  2. (int x) => x - 1
  3. A function that takes a String and returns an int.
  4. Closure: () => int; 5.
  5. A lambda that where calls for each item to decide whether to keep it.

Key Takeaways

  • In Dart, functions are values: they can be stored in variables.
  • A lambda is a nameless function: (params) { ... } or (params) => expr.
  • Call it with (); printing it without () shows the function itself.
  • Function types look like int Function(int).
  • The where, map and sort arguments you've used are lambdas.