On this page11 sections
Lecture 039: Lambdas
| Day | 14: Lambdas, Higher-Order Functions & Closures |
| Lecture | 039 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Since Day 5 you've been writing little things like
(n) => n > 10insidewhere. 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,sortandmap
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:
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)); // 25The shape is (parameters) { body } or (parameters) => expression. Note the ; after the
lambda: it ends the var statement.
2. Parameters Work as Usual
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:
int Function(int) triple = (n) => n * 3;
print(triple(4)); // 12
print(squareArrow.runtimeType); // (int) => intint 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
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
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
AYESHA KHAN | initials: AK | long: true
BILAL AHMED | initials: BA | long: true
ZARA | initials: Z | long: falseinitials 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
var greet = () => 'Hi';
print(greet);Output
Closure: () => StringThat's the function itself. Call it: print(greet());.
2. Wrong argument types
var add = (int a, int b) => a + b;
print(add(1, 'x'));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
- Write a lambda
isEventhat returns whether anintis even. - Rewrite
(int x) { return x - 1; }in arrow form. - What does
int Function(String)describe? - What's printed by
var f = () => 5; print(f);? And byprint(f());? - In
list.where((n) => n > 3), what is(n) => n > 3?
Practice Answers
var isEven = (int n) => n % 2 == 0;(int x) => x - 1- A function that takes a
Stringand returns anint. Closure: () => int;5.- A lambda that
wherecalls 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,mapandsortarguments you've used are lambdas.