Working with Core Types and Optics
Match, extract and modify the value inside a Maybe, Either, Validated or Try with optics.

- Extract a case of
Maybe,Either,ValidatedorTrywith a prism fromPrisms, and build one back - Modify the value inside a
Justor aRightwithMaybeTraversalsandEitherTraversals, leaving the other case untouched - Compose
MaybeTraversals.just()into a lens path to read through aMaybemidway along it - Filter and count a list of
Tryresults with a prism'sgetOptionalandmatches - Choose between core type prisms and Optics Extensions for the task in hand
As you've learnt from the previous chapters, optics provide a powerful way to focus on and modify immutable data structures. But what happens when the data you're working with is wrapped in Higher-Kinded-J's core types (Maybe, Either, Validated, or Try)?
Traditional optics work brilliantly with straightforward, deterministic data. However, real-world applications rarely deal with such certainty. Fields might be null, operations might fail, validation might produce errors, and database calls might throw exceptions. Handling these scenarios whilst maintaining clean, composable optics code requires a bridge between these two powerful abstractions.
This is where Core Type Integration comes in.
The Challenge
Consider a typical scenario: updating a user profile where some fields are optional, validation might fail, and the database operation might throw an exception.
public ProfileOwner updateUserProfile(ProfileOwner user, String newEmail) {
// Null checking
if (user == null || user.getProfile() == null) {
return null; // Or throw exception?
}
// Validation
if (newEmail == null || !newEmail.contains("@")) {
throw new ValidationException("Invalid email");
}
// Try to update
try {
String validated = validateEmailFormat(newEmail);
Profile updated = user.getProfile().withEmail(validated);
return user.withProfile(updated);
} catch (Exception e) {
// Now what? Log and return null? Re-throw?
log.error("Failed to update email", e);
return null;
}
}
This code is a mess of concerns: null handling, validation logic, exception management, and the actual update logic are all tangled together.
public Either<String, ProfileOwner> updateUserProfile(ProfileOwner user, String newEmail) {
Lens<ProfileOwner, Profile> profileLens = ProfileOwnerLenses.profile();
Lens<Profile, String> emailLens = ProfileLenses.email();
Lens<ProfileOwner, String> userToEmail = profileLens.andThen(emailLens);
return modifyEither(
userToEmail,
email -> validateEmail(email),
user
);
}
private Either<String, String> validateEmail(String email) {
if (email == null || !email.contains("@")) {
return Either.left("Invalid email format");
}
return Either.right(email.toLowerCase());
}
Clean separation of concerns:
- Optics define the path to the data
- Core types handle the errors
- Business logic stays pure and testable
Without these, a Maybe or an Either in the middle of a path forces you out of the optic and into unwrap-check-rewrap by hand, which is exactly the ceremony optics exist to remove. With them, a core type is just another sum type: Right is a variant like any other, so a path can run straight through it and the absent case stays a no-op rather than becoming a branch.
Two Complementary Approaches
Higher-Kinded-J provides two integrated solutions for working with core types and optics:
1. Core Type Prisms: Pattern Matching on Functional Types
Extract values from Maybe, Either, Validated, and Try using prisms, just as you would with sealed interfaces.
Prism<Maybe<ProfileOwner>, ProfileOwner> justPrism = Prisms.just();
Prism<Try<Order>, Order> successPrism = Prisms.success();
// Extract user if present
Optional<ProfileOwner> user = justPrism.getOptional(maybeUser);
// Extract order if successful
Optional<Order> order = successPrism.getOptional(tryOrder);
Best for: Safe extraction and pattern matching on core types, composing with other optics.
2. Optics Extensions: Safety Rails for Lens and Traversal
Augment lenses and traversals with built-in null safety, validation, and exception handling.
Lens<ProfileOwner, String> emailLens = ProfileOwnerLenses.email();
// Null-safe access
Maybe<String> email = getMaybe(emailLens, user);
// Validated modification
Either<String, ProfileOwner> updated = modifyEither(
emailLens,
address -> address.contains("@")
? Either.right(address.toLowerCase())
: Either.left("Invalid email format"),
user
);
// Bulk validation with error accumulation
Validated<List<String>, List<Order>> result = modifyAllValidated(
allPrices,
price -> validatePrice(price),
orders
);
Best for: Individual field operations with validation, bulk operations, exception handling.
Optics Extensions are covered on their own page.
Core Type Prisms in Detail
Prisms focus on one case of a sum type. They're perfect for safely extracting values from Maybe, Either, Validated, and Try without verbose pattern matching or null checks.
Maybe Prisms
// Extract value from Just, returns empty Optional for Nothing
Prism<Maybe<String>, String> justPrism = Prisms.just();
Maybe<String> present = Maybe.just("Hello");
Maybe<String> absent = Maybe.nothing();
Optional<String> value = justPrism.getOptional(present);
// Optional[Hello]
Optional<String> empty = justPrism.getOptional(absent);
// Optional.empty
// Construct Maybe.just() from a value
Maybe<String> built = justPrism.build("World");
// Just(World)
// Check if it's a Just
boolean isJust = justPrism.matches(present);
// true
Either Prisms
// Extract from Left and Right cases
Prism<Either<String, Integer>, String> leftPrism = Prisms.left();
Prism<Either<String, Integer>, Integer> rightPrism = Prisms.right();
Either<String, Integer> success = Either.right(42);
Either<String, Integer> failure = Either.left("AppError");
// Extract success value
Optional<Integer> value = rightPrism.getOptional(success);
// Optional[42]
Optional<Integer> noValue = rightPrism.getOptional(failure);
// Optional.empty
// Extract error value
Optional<String> error = leftPrism.getOptional(failure);
// Optional[AppError]
// Construct Either values
Either<String, Integer> newSuccess = rightPrism.build(100);
// Right(100)
Validated Prisms
// Extract from Valid and Invalid cases
Prism<Validated<String, Integer>, Integer> validPrism = Prisms.valid();
Prism<Validated<String, Integer>, String> invalidPrism = Prisms.invalid();
Validated<String, Integer> valid = Validated.valid(30);
Validated<String, Integer> invalid = Validated.invalid("Age must be positive");
// Extract valid value
Optional<Integer> age = validPrism.getOptional(valid);
// Optional[30]
// Extract validation error
Optional<String> error = invalidPrism.getOptional(invalid);
// Optional[Age must be positive]
Try Prisms
// Extract from Success and Failure cases
Prism<Try<Integer>, Integer> successPrism = Prisms.success();
Prism<Try<Integer>, Throwable> failurePrism = Prisms.failure();
Try<Integer> success = Try.success(42);
Try<Integer> failure = Try.failure(new RuntimeException("Database error"));
// Extract success value
Optional<Integer> value = successPrism.getOptional(success);
// Optional[42]
// Extract exception
Optional<Throwable> ex = failurePrism.getOptional(failure);
// Optional[java.lang.RuntimeException: Database error]
Core Type Traversals
Whilst prisms extract values, traversals modify values inside core types. MaybeTraversals and EitherTraversals live in org.higherkindedj.optics.util, beside Prisms:
Maybe Traversals
Traversal<Maybe<String>, String> justTraversal = MaybeTraversals.just();
// Modify value inside Just
Maybe<String> original = Maybe.just("hello");
Maybe<String> modified = Traversals.modify(justTraversal, String::toUpperCase, original);
// Result: Just(HELLO)
// No effect on Nothing
Maybe<String> nothing = Maybe.nothing();
Maybe<String> unchanged = Traversals.modify(justTraversal, String::toUpperCase, nothing);
// Result: Nothing
Either Traversals
Traversal<Either<String, Integer>, Integer> rightTraversal = EitherTraversals.right();
Traversal<Either<String, Integer>, String> leftTraversal = EitherTraversals.left();
// Modify Right value
Either<String, Integer> success = Either.right(100);
Either<String, Integer> doubled = Traversals.modify(rightTraversal, n -> n * 2, success);
// Result: Right(200)
// AppError enrichment with Left traversal
Either<String, Integer> error = Either.left("Connection failed");
Either<String, Integer> enriched =
Traversals.modify(leftTraversal, msg -> "[ERROR] " + msg, error);
// Result: Left([ERROR] Connection failed)
The EitherTraversals.left() traversal is excellent for adding context to error messages without unwrapping the Either.
Composition: The Real Power
Prisms compose seamlessly with lenses and other optics to navigate deeply nested structures. Here an API response may carry an Order, the chapter's running example:
@GenerateLenses
record OrderReply(int statusCode, Maybe<Order> data, List<String> warnings) {}
A Maybe traversal between the response's lens and the order's lenses reaches the customer's email:
// Full composition: OrderReply -> Maybe<Order> -> Order -> Customer -> email
Lens<OrderReply, Maybe<Order>> dataLens = OrderReplyLenses.data();
Traversal<Maybe<Order>, Order> orderTraversal = MaybeTraversals.just();
Lens<Order, Customer> customerLens = OrderLenses.customer();
Lens<Customer, String> emailLens = CustomerLenses.email().andThen(EmailAddressLenses.value());
Traversal<OrderReply, String> emailPath =
dataLens.andThen(orderTraversal).andThen(customerLens).andThen(emailLens);
List<String> emails = Traversals.getAll(emailPath, response);
// Result: [ada@example.com] for Ada's order, or [] when the response carries no order
Processing Collections of Core Types
Prisms excel at filtering and extracting from collections:
List<Try<ProfileOwner>> dbResults = loadUsersFromDatabase(userIds);
Prism<Try<ProfileOwner>, ProfileOwner> successPrism = Prisms.success();
Prism<Try<ProfileOwner>, Throwable> failurePrism = Prisms.failure();
// Get all successfully loaded users
List<ProfileOwner> users = dbResults.stream()
.flatMap(result -> successPrism.getOptional(result).stream())
.toList();
// Count successes
long successCount = dbResults.stream()
.filter(successPrism::matches)
.count();
// Log all errors
dbResults.stream()
.flatMap(result -> failurePrism.getOptional(result).stream())
.forEach(error -> logger.error("Database error: {}", error.getMessage()));
When to Use Each Approach
Use Core Type Prisms when
- Extracting values from
Maybe,Either,Validated, orTry - Pattern matching on functional types without
instanceof - Composing core types with other optics for deep navigation
- Processing collections of core type values
Use Optics Extensions when
- Accessing potentially null fields
- Validating single field or bulk updates
- Performing operations that might throw exceptions
- Choosing between first-error and error-accumulation strategies
- CoreTypePrismsExample: API response processing
- LensExtensionsExample: affiliate validation
- TraversalExtensionsExample: bulk order processing
- IntegrationPatternsExample: complete e-commerce workflow
Common Pitfalls
Whilst all core type families work with optics, mixing them inappropriately can lead to confusing code:
// Confusing: Mixing Maybe and Either unnecessarily
Maybe<Either<String, ProfileOwner>> findUser(String id);
// Better: Choose one based on your needs
Either<String, ProfileOwner> loadUser(String id); // If you have an error message
Maybe<ProfileOwner> lookUpUser(String id); // If it's just presence/absence
When in doubt, start with Either. It's the most versatile:
- Carries error information (unlike
Maybe) - Fails fast (unlike
Validated) - Doesn't catch exceptions automatically (unlike
Try)
You can always switch to Validated for error accumulation or Try for exception handling when needed.
Remember that prism.getOptional() returns Java's Optional, not Maybe:
Prism<Maybe<String>, String> justPrism = Prisms.just();
Maybe<String> maybeValue = Maybe.just("Hello");
// Returns Optional, not Maybe
Optional<String> value = justPrism.getOptional(maybeValue);
// Convert back to Maybe if needed
Maybe<String> backToMaybe = value
.map(Maybe::just)
.orElse(Maybe.nothing());
- A core type is just another sum type.
Maybe,Either,ValidatedandTryeach get prisms for their cases, so matching one is the same operation as matching any sealed hierarchy. - Prisms answer, traversals act.
matches()andgetOptional()interrogate a case; the matching traversal modifies the value inside it and leaves the other case untouched. - They compose with the optics you already have. A prism into a
Rightis a legal middle step in a longer path, which is what turns "unwrap, check, rewrap" into one expression. getOptional()speaksOptional, notMaybe. The optics surface is uniform on the JDK type, so converting back is an explicitmap/orElsestep.- Absence stays absent. Modifying through the wrong case is a no-op rather than an error, so a
Leftsurvives aRight-targeted update unchanged.
- Prisms: the optic these instances are built from
- Optics Extensions: the validated
LensandTraversaloperations that pair with them - Deep Validation with
modifyF: the longer example that puts a prism in the middle of a longer path
Previous: Kind Field Support Next: Optics Extensions