a java sealed interface called Result that has Some and None records as implementations, with of() that returns one of the two, and allows returning an Optional for chaining the code is as follows: package com.arch.util.result; import java.util.Optional; /** * A sealed interface hierarchy to represent to existence or lack of a value, * for use in destructuring * * Returning a Result.of(value) or Result.empty() will give the ability to * destructure like: * * <pre> * if(result instanceof Some(File found)){ * // code with the found File in scope * } * </pre> * * Or * * <pre> * return switch(someOperation()){ * Some(String message) -> message; * None() -> "Nothing??"; * }; * </pre> * * Results can be used directly with {@link Optional}<T> values, present or not, * and can be easily converted to and from */ public sealed interface Result<T> permits Some, None { public static <T> Result<T> of(Optional<T> value){ return value.map(Result::of).orElseGet(Result::empty); } public static <T> Result<T> of(T value){ return value == null ? new None<>() : new Some<>(value); } public static <T> None<T> empty(){ return new None<>(); } public abstract Optional<T> toOptional(); }
https://media.chitter.xyz/media_attachments/files/111/484/341/936/988/424/original/3f22f02ca9d3dfa8.png