Affines: A Practical Guide

Read and update a field that may be absent, such as an Optional component, without flatMap chains.

What You'll Learn

  • Build an affine with Affines.some(), Affines.nullable() or Affines.listAt, or by composing a lens with a prism
  • Predict why Lens.andThen(Prism) gives an Affine rather than a Traversal
  • Update a nested optional field with modify and modifyWhen, which leave an absent value alone
  • Predict what set does on an absent focus, and check an affine with AffineLaws.assertAffineLaws
  • Choose between an affine, a prism, a lens and a traversal for a field

See Example Code

We've seen how a Lens focuses on exactly one value that is guaranteed to exist, and how a Prism focuses on a value that may or may not exist depending on the variant.

But what about fields that are sometimes there? Optional fields in records, nullable properties in legacy APIs, or the result of composing a Lens with a Prism? This is the domain of the Affine.

An affine plays the part of an accessor that returns Optional, paired with a copy that writes the value back. Unlike the hand-written pair, it composes with other optics, and modify leaves an absent value alone. Choosing an optic sets it beside the other optic types.


The Scenario: Optional Fields in Records

Modern Java applications frequently use Optional<T> to represent values that may be absent. The chapter's customer profile has an optional nickname and an optional second email:

@GenerateLenses
@GenerateFocus
public record CustomerProfile(
    String name, Optional<String> nickname, Optional<EmailAddress> altEmail) {}

A product review may be anonymous, so its author is optional too:

record Review(String sku, Optional<CustomerProfile> author) {}

Our Goal: We need to safely access and update the reviewer's nickname, which is doubly optional: the review might be anonymous, and even if it is not, its author might have no nickname.


Where an Affine Comes From

In Java the optic types are siblings, not subtypes (How the optic types relate), so a method that takes an Affine will not accept a Lens. You compose your way to an Affine.

Key insight: When you compose a Lens (exactly one element) with a Prism (zero or one element), the result focuses on zero or one element, which is an Affine.

OpticFocusGetSet
LensExactly oneAlways succeedsAlways succeeds
PrismZero or oneMay failNo set: build makes a whole from a part, modify changes a match
AffineZero or oneMay failWrites into a structure you already have
TraversalZero or moreMultiple valuesMultiple values

A Step-by-Step Walkthrough

Step 1: Creating an Affine Manually

An Affine is defined by two operations:

  • getOptional(source): Returns Optional<A> containing the focus if present
  • set(value, source): Returns a new source with the focus updated
    // Affine for accessing the value inside an Optional field
    Affine<Optional<String>, String> someAffine =
        Affine.of(
            Function.identity(), // getOptional: Optional<String> -> Optional<String>
            (opt, value) -> Optional.of(value)); // set: always wrap in Optional.of

    // Usage
    Optional<String> present = Optional.of("hello");
    Optional<String> result = someAffine.getOptional(present); // Optional.of("hello")

    Optional<String> empty = Optional.empty();
    Optional<String> noMatch = someAffine.getOptional(empty); // Optional.empty()

    // Setting always wraps the value
    Optional<String> updated = someAffine.set("world", empty); // Optional.of("world")

Step 2: Using the Affines Utility Class

The Affines utility class provides ready-made affines for common patterns:

import org.higherkindedj.optics.util.Affines;

// For Optional<T> fields
Affine<Optional<String>, String> someAffine = Affines.some();

// For Maybe<T> (higher-kinded-j's Maybe type)
Affine<Maybe<String>, String> justAffine = Affines.just();

// For nullable fields (legacy code)
Affine<@Nullable String, String> nullableAffine = Affines.nullable();

// For list element access
Affine<List<String>, String> headAffine = Affines.listHead();
Affine<List<String>, String> lastAffine = Affines.listLast();
Affine<List<String>, String> thirdAffine = Affines.listAt(2);

Step 3: Affine from Lens + Prism Composition

The most common way to obtain an Affine is through composition:

    // Domain model
    record DatabaseSettings(String host, int port) {}
    record Config(Optional<DatabaseSettings> database) {}

    // The lens always reaches the Optional<DatabaseSettings> field
    Lens<Config, Optional<DatabaseSettings>> databaseLens =
        Lens.of(Config::database, (c, db) -> new Config(db));

    // The prism may or may not find DatabaseSettings inside the Optional
    Prism<Optional<DatabaseSettings>, DatabaseSettings> somePrism = Prisms.some();

    // Composition: Lens.andThen(Prism) = Affine
    Affine<Config, DatabaseSettings> databaseAffine = databaseLens.andThen(somePrism);

    // Usage
    Config config1 = new Config(Optional.of(new DatabaseSettings("localhost", 5432)));
    Optional<DatabaseSettings> result1 = databaseAffine.getOptional(config1);
    // result1 = Optional[DatabaseSettings[host=localhost, port=5432]]

    Config config2 = new Config(Optional.empty());
    Optional<DatabaseSettings> result2 = databaseAffine.getOptional(config2);
    // result2 = Optional.empty, since the prism found nothing

    // Setting through the affine: some() can build the Optional, so the empty one is filled
    Config updated = databaseAffine.set(new DatabaseSettings("newhost", 3306), config2);
    // updated = Config[database=Optional[DatabaseSettings[host=newhost, port=3306]]]

The affine's path ends inside an Optional that may hold nothing:

Why Affine, not Traversal?

You might wonder why Lens.andThen(Prism) returns an Affine rather than a Traversal. The answer is precision:

  • Traversal focuses on zero or more elements
  • Affine focuses on exactly zero or one element

Since a Lens always provides one element and a Prism may match zero or one, the composition can never produce more than one element. Affine captures this constraint precisely, giving you stronger type guarantees.


Affine vs Prism: The Key Difference

Both Affine and Prism focus on zero-or-one elements, but they differ in what they can write:

OperationPrismAffine
getOptional✅ Yes✅ Yes
set❌ No (modify changes a match)✅ Yes
build✅ Yes (construct from part)❌ No

A Prism can construct a complete structure from just the focused part (via build). An Affine cannot; it writes into a structure you already have.

// Prism: can build from scratch
Prism<Shape, Circle> circlePrism = ShapePrisms.circle();
Shape newCircle = circlePrism.build(new Circle(5.0, "red"));

// Affine: cannot build, only update
Affine<Config, DatabaseSettings> dbAffine = databaseLens.andThen(somePrism);
// No build() method available; must have an existing Config to work with
Config updated = dbAffine.set(newSettings, existingConfig);

When to use which:

  • Use Prism for sum types where you can construct variants
  • Use Affine for optional fields in product types

Convenience Methods

The Affine interface provides several convenience methods for common operations:

Quick Reference:

MethodPurposeReturns
matches(S source)Check if affine focuses on a valueboolean
doesNotMatch(S source)Check if affine has no focusboolean
getOrElse(A default, S source)Extract value or return defaultA
mapOptional(Function<A, B> f, S source)Transform focused valueOptional<B>
modify(Function<A, A> f, S source)Modify if present, else return originalS
modifyWhen(Predicate<A> p, Function<A, A> f, S source)Modify only when predicate satisfiedS
setWhen(Predicate<A> p, A value, S source)Set only when predicate satisfiedS
remove(S source)Remove the focused element (if supported)S

Checking for Presence

    Affine<Optional<String>, String> someAffine = Affines.some();

    Optional<String> present = Optional.of("hello");
    Optional<String> empty = Optional.empty();

    // Using matches()
    if (someAffine.matches(present)) {
      System.out.println("Value present");
    }

    // Using doesNotMatch()
    if (someAffine.doesNotMatch(empty)) {
      System.out.println("No value");
    }

    // Useful in streams
    List<Optional<String>> values = List.of(Optional.of("a"), Optional.empty(), Optional.of("b"));

    long presentCount = values.stream().filter(someAffine::matches).count(); // 2

Default Values

Affine<Optional<Config>, Config> configAffine = Affines.some();

Optional<Config> maybeConfig = loadConfig();

// Get value or use default
Config config = configAffine.getOrElse(Config.DEFAULT, maybeConfig);

Conditional Modification

    Affine<Optional<String>, String> someAffine = Affines.some();

    Optional<String> value = Optional.of("hello world");

    // Only modify if predicate is satisfied
    Optional<String> result =
        someAffine.modifyWhen(s -> s.length() > 5, String::toUpperCase, value);
    // result = Optional.of("HELLO WORLD")

    // Set only when condition is met
    Optional<String> guarded = someAffine.setWhen(s -> s.startsWith("hello"), "goodbye", value);
    // guarded = Optional.of("goodbye")

Removal Support

Some affines support the remove operation to clear the focused element:

    // Create an affine that supports removal
    Affine<Optional<String>, String> removableAffine = Affines.someWithRemove();

    Optional<String> present = Optional.of("hello");
    Optional<String> cleared = removableAffine.remove(present);
    // cleared = Optional.empty()

Remove Support

Not all affines support the remove operation. Calling remove on an affine that doesn't support it throws an UnsupportedOperationException. Use Affines.someWithRemove() instead of Affines.some() when you need removal support.


Composing Affines

Affines compose with other optics following precise rules:

// Affine.andThen(Affine) = Affine
Affine<A, C> withAffine = affineAB.andThen(affineBC);

// Affine.andThen(Lens) = Affine
Affine<A, C> withLens = affineAB.andThen(lensBC);

// Affine.andThen(Prism) = Affine
Affine<A, C> withPrism = affineAB.andThen(prismBC);

// Affine.andThen(Iso) = Affine
Affine<A, C> withIso = affineAB.andThen(isoBC);

// Affine.andThen(Traversal) = Traversal
Traversal<A, C> withTraversal = affineAB.andThen(traversalBC);

Deep Optional Access Example

    // A product review, whose author is absent when it is anonymous
    record Review(String sku, Optional<CustomerProfile> author) {}

    // Build affines for each optional field
    Lens<Review, Optional<CustomerProfile>> authorLens =
        Lens.of(Review::author, (r, a) -> new Review(r.sku(), a));

    Lens<CustomerProfile, Optional<String>> nicknameLens = CustomerProfileLenses.nickname();

    Prism<Optional<CustomerProfile>, CustomerProfile> authorPrism = Prisms.some();
    Prism<Optional<String>, String> nicknamePrism = Prisms.some();

    // Compose to access nested optional
    Affine<Review, String> authorNickname =
        authorLens
            .andThen(authorPrism) // Lens.andThen(Prism) = Affine
            .andThen(nicknameLens) // Affine.andThen(Lens) = Affine
            .andThen(nicknamePrism); // Affine.andThen(Prism) = Affine

    // Usage
    CustomerProfile ada = new CustomerProfile("Ada", Optional.of("Countess"), Optional.empty());
    Review signed = new Review("LAMP", Optional.of(ada));
    Review anonymous = new Review("BULB", Optional.empty());

    Optional<String> nickname1 = authorNickname.getOptional(signed);
    // Optional.of("Countess")

    Optional<String> nickname2 = authorNickname.getOptional(anonymous);
    // Optional.empty()

    // Update deeply nested optional
    Review updated = authorNickname.set("Lady Lovelace", signed);
    // Review[sku=LAMP, author=Optional[CustomerProfile[name=Ada,
    //   nickname=Optional[Lady Lovelace], altEmail=Optional.empty]]]

Factory Methods

The Affine interface provides factory methods for common construction patterns:

From Getter and Setter

// Basic construction
Affine<S, A> affine = Affine.of(
    s -> getOptional(s),           // S -> Optional<A>
    (s, a) -> setInSource(s, a)    // (S, A) -> S
);

// With removal support
Affine<S, A> removable = Affine.of(
    s -> getOptional(s),           // S -> Optional<A>
    (s, a) -> setInSource(s, a),   // (S, A) -> S
    s -> removeFromSource(s)       // S -> S
);

From Lens and Prism

// Compose a Lens and Prism into an Affine
Affine<A, C> fromLens = Affine.fromLensAndPrism(
    lensAB,   // Lens<A, B>
    prismBC   // Prism<B, C>
);

// Compose a Prism and Lens into an Affine
Affine<A, C> fromPrism = Affine.fromPrismAndLens(
    prismAB,  // Prism<A, B>
    lensBC    // Lens<B, C>
);

When to Use Affines vs Other Optics

Use Affine When

  • Optional fields in records or classes (Optional<T>)
  • Nullable properties in legacy or interop code
  • Conditional field access that may or may not exist
  • Lens + Prism compositions where you need the precise type
// Perfect for optional record fields
@GenerateLenses
record ApiConfig(Optional<String> apiKey) {}

Affine<ApiConfig, String> apiKeyAffine =
    ApiConfigLenses.apiKey().andThen(Prisms.some());

Optional<String> key = apiKeyAffine.getOptional(new ApiConfig(Optional.of("secret")));

Use Lens When

  • The field is always present (guaranteed to exist)
  • You're working with product types (records, classes)
// Field always exists
record Point(int x, int y) {}
Lens<Point, Integer> xLens = Lens.of(Point::x, (p, x) -> new Point(x, p.y()));

Use Prism When

  • Working with sum types (sealed interfaces, enums)
  • You need to construct the whole from a part
  • Type-safe variant matching
// Sum type handling
@GeneratePrisms
sealed interface Shape permits Circle, Rectangle {}

Prism<Shape, Circle> circlePrism = ShapePrisms.circle();
Shape circle = circlePrism.build(new Circle(5.0, "red"));  // Can construct!

Use Traversal When

  • Focusing on multiple elements (lists, sets)
  • You need to work with collections
// Multiple elements
Traversal<List<String>, String> listTraversal = Traversals.forList();
List<String> upper = Traversals.modify(listTraversal, String::toUpperCase, names);

Common Pitfalls

Don't Do This

// AppConfig is the configuration example's model, at the end of this page

// Overly complex: manual Optional handling
Optional<String> poolMaxOf(AppConfig config) {
    return config.database()
        .flatMap(db -> db.pool())
        .map(pool -> pool.maxSize())
        .map(Object::toString);
}

// Unsafe: assuming presence without checking
String hostOf(AppConfig config) {
    return config.database().get().host();  // NoSuchElementException!
}

// Verbose: repeated null checks, on a legacy model whose fields may be null
String nicknameOf(LegacyReview review) {
    if (review.author() != null && review.author().nickname() != null) {
        return review.author().nickname();
    }
    return "";
}

Do This Instead

// Clean: compose affines for deep access
Affine<AppConfig, Integer> poolMaxAffine =
    databaseAffine
        .andThen(pool)
        .andThen(Affines.some())
        .andThen(maxSize);

Optional<String> poolMax = poolMaxAffine.mapOptional(Object::toString, config);

// Safe: affine handles absence gracefully
String value = databaseAffine.getOrElse(defaultDatabase, config).host();

// Composable: build reusable optics
Affine<Review, String> nicknameAffine = ReviewOptics.AUTHOR_NICKNAME;
Optional<String> nickname = nicknameAffine.getOptional(review);

The Affine Laws

Every affine the library builds satisfies these three laws, with one exception: TraversalPath.headOption() reads the first element and writes every element, so Get-Set fails when the elements differ.

Get-Set Law

If a value is present, getting and then setting returns the original:

affine.getOptional(s).map(a -> affine.set(a, s)).orElse(s) == s

Set-Set Law

Setting twice is equivalent to setting once with the final value:

affine.set(b, affine.set(a, s)) == affine.set(b, s)

Set-Get Law

When the focus is present, setting a value and then getting returns that value:

// Whenever affine.getOptional(s) is present:
affine.getOptional(affine.set(a, s)) == Optional.of(a)

When the focus is absent

Neither Get-Set nor Set-Get covers set on an absent focus, and affines differ there. One whose last step can build the value writes it, provided every step before that is present: Affines.some().set("x", Optional.empty()) returns Optional.of("x"). A Lens.andThen(Prism) affine likewise replaces whatever variant is present with the one the prism builds. One that cannot build, such as an index past the end of a list, returns the structure unchanged, and so does a path whose earlier step is absent. The Focus DSL page gives the rule by position along a path. When you mean "only if it is there", use modify: it never writes to an absent focus.

Two weaker laws do hold on an absent focus for every affine: modify changes nothing, and set either changes nothing or writes a value that reads back. Set-Set holds there too. hkj-test's AffineLaws.assertAffineLaws checks all of these as well as the three laws on a present focus. For an affine that must also leave an absent focus alone on set, add AffineLaws.assertSetNoOpWhenAbsent.


Real-World Example: Configuration Management

import java.util.Optional;
import org.higherkindedj.optics.Affine;
import org.higherkindedj.optics.Lens;
import org.higherkindedj.optics.util.Prisms;

// Domain model with nested optionals
record AppConfig(String appName, Optional<DatabaseConfig> database, Optional<CacheConfig> cache) {}

record DatabaseConfig(String host, int port, Optional<PoolConfig> pool) {}

record PoolConfig(int minSize, int maxSize) {}

record CacheConfig(String provider, int ttlSeconds) {}


public class ConfigOptics {
  // Lenses for required fields
  public static final Lens<AppConfig, String> appName =
      Lens.of(AppConfig::appName, (c, n) -> new AppConfig(n, c.database(), c.cache()));

  public static final Lens<AppConfig, Optional<DatabaseConfig>> database =
      Lens.of(AppConfig::database, (c, db) -> new AppConfig(c.appName(), db, c.cache()));

  public static final Lens<DatabaseConfig, String> host =
      Lens.of(DatabaseConfig::host, (db, h) -> new DatabaseConfig(h, db.port(), db.pool()));

  public static final Lens<DatabaseConfig, Optional<PoolConfig>> pool =
      Lens.of(DatabaseConfig::pool, (db, p) -> new DatabaseConfig(db.host(), db.port(), p));

  public static final Lens<PoolConfig, Integer> maxSize =
      Lens.of(PoolConfig::maxSize, (p, m) -> new PoolConfig(p.minSize(), m));

  // Affines for optional access
  public static final Affine<AppConfig, DatabaseConfig> databaseAffine =
      database.andThen(Prisms.some());

  public static final Affine<AppConfig, String> databaseHost = databaseAffine.andThen(host);

  public static final Affine<AppConfig, PoolConfig> poolConfig =
      databaseAffine.andThen(pool).andThen(Prisms.some());

  public static final Affine<AppConfig, Integer> poolMaxSize = poolConfig.andThen(maxSize);

  public static void main(String[] args) {
    // Create a config with nested optionals
    AppConfig config =
        new AppConfig(
            "MyApp",
            Optional.of(new DatabaseConfig("localhost", 5432, Optional.of(new PoolConfig(5, 20)))),
            Optional.empty());

    // Read nested values safely
    Optional<String> configHost = databaseHost.getOptional(config);
    // Optional[localhost]
    System.out.println("Host: " + configHost);

    Optional<Integer> poolMax = poolMaxSize.getOptional(config);
    // Optional[20]
    System.out.println("Pool max: " + poolMax);

    // Update deeply nested value
    AppConfig updated = poolMaxSize.set(50, config);
    Optional<Integer> updatedMax = poolMaxSize.getOptional(updated);
    // Optional[50]
    System.out.println("Updated pool max: " + updatedMax);

    // Conditional modification
    AppConfig doubled = poolMaxSize.modify(n -> n * 2, config);
    Optional<Integer> doubledMax = poolMaxSize.getOptional(doubled);
    // Optional[40]
    System.out.println("Doubled pool max: " + doubledMax);

    // Safe operation on missing config: no database reads as empty, and nothing throws
    AppConfig emptyConfig = new AppConfig("EmptyApp", Optional.empty(), Optional.empty());
    boolean hostMissing = databaseHost.getOptional(emptyConfig).isEmpty();
    // true
    System.out.println("Missing host: " + hostMissing);

    // Modification on missing does nothing
    AppConfig unchanged = poolMaxSize.modify(n -> n * 2, emptyConfig);
    boolean sameConfig = unchanged == emptyConfig;
    // true
    System.out.println("Empty config unchanged: " + sameConfig);
  }
}

Key Takeaways

  • An Affine focuses on exactly zero or one value: getOptional may come back empty, and updates go through an existing structure (there is no build from nothing)
  • It is the honest type for Lens-then-Prism: the composition can never produce more than one focus, and Affine says so more precisely than Traversal would
  • Optional fields without the flatMap chains: compose affines through nested Optionals and the absence handling is done once, in the optic
  • Prism constructs, Affine only updates: reach for a Prism on sum types you can build; reach for an Affine on optional fields inside product types

See Also


Further Reading

Terminology Note

In some functional programming libraries (notably Scala's Monocle), the Affine optic is called an Optional. This can cause confusion with Java's java.util.Optional. In higher-kinded-j, we use the term "Affine" to avoid this ambiguity whilst maintaining mathematical precision.

Hands-On Learning

Practise affine basics in Tutorial 04: Affine Basics (7 exercises).


Previous: Advanced Prism Patterns: Recipes Next: Isomorphisms