then<SubPart> method
Composes this lens with another lens to focus deeper.
Creates a new lens that focuses on a SubPart of the Part that this
lens focuses on. This enables "zooming in" through multiple levels of
nested data structures.
If lens1: Whole → Part and lens2: Part → SubPart, then
lens1.then(lens2): Whole → SubPart.
Composition semantics:
- Get: Chains the get functions:
other.get(get(w))First get the part from the whole, then get the subpart from the part. - Set: Carefully updates through both layers:
- Get the current part:
get(w) - Update the subpart within it:
other.set(get(w), sp) - Update the whole with the modified part:
set(w, ...)
- Get the current part:
This maintains the lens laws and allows safe composition of lenses.
Example:
final personCityLens = personLens.then(addressLens).then(cityLens);
final updated = personCityLens.set(person, 'Boston');
Type parameter SubPart is the type of the deeper focus.
Implementation
Lens<Whole, SubPart> then<SubPart>(Lens<Part, SubPart> other) => Lens(
get: (w) => other.get(get(w)),
set: (w, sp) => set(w, other.set(get(w), sp)),
);