then<SubPart> method

Lens<Whole, SubPart> then<SubPart>(
  1. Lens<Part, SubPart> other
)

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:
    1. Get the current part: get(w)
    2. Update the subpart within it: other.set(get(w), sp)
    3. Update the whole with the modified part: set(w, ...)

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)),
);