This project provides a Java implementation of Scala's Either type, a functional data structure representing a value of one of two possible types (a disjoint union). By convention, Left represents failure/error cases and Right represents success cases.
either/
├── src/main/java/stream/header/
│ └── Either.java # Main Either implementation
├── pom.xml # Maven configuration
└── CLAUDE.md # This file
- Language: Java 17+
- Build Tool: Maven (use
./mvnwwrapper) - Package:
stream.header - Main Class:
Either<L, R>(sealed interface withLeftandRightrecords)
Either<String, Integer> right = Either.right(42);
Either<String, Integer> left = Either.left("error");map(Function)- Transform Right valueflatMap(Function)- Chain Either-returning operationsmapLeft(Function)- Transform Left valuefold(Function, Function)- Pattern match on Left or RightgetOrElse(T)- Extract Right or default valuefilterOrElse(Predicate, Supplier)- Filter Right value
isLeft()/isRight()- Check which sidecontains(R)- Check if Right equals valueexists(Predicate)- Test Right valuegetLeft()/getRight()- Unsafe extraction (throws if wrong side)
toOptional()- Convert Right to OptionaltoOptionalLeft()- Convert Left to Optionalswap()- Exchange Left and Right
forEach(Consumer)- Apply action to RightforEachLeft(Consumer)- Apply action to Left
# Compile
./mvnw compile
# Run tests
./mvnw test
# Package
./mvnw package
# Clean
./mvnw clean- Sealed Interface: Uses Java 17 sealed interfaces for exhaustive pattern matching
- Records: Left and Right are immutable records
- Right-biased: All monadic operations (map, flatMap) operate on Right, matching modern Scala behavior
- Null Safety: Both Left and Right reject null values
- Fail-fast: Methods validate null parameters immediately
import stream.header.Either;
public class Example {
public static Either<String, Integer> divide(int a, int b) {
if (b == 0) {
return Either.left("Division by zero");
}
return Either.right(a / b);
}
public static void main(String[] args) {
Either<String, Integer> result = divide(10, 2)
.map(x -> x * 2)
.flatMap(x -> divide(x, 5));
String message = result.fold(
error -> "Error: " + error,
value -> "Result: " + value
);
System.out.println(message); // "Result: 4"
}
}- Left: Represents errors, failures, or exceptional cases (typically
String,Exception, or custom error types) - Right: Represents successful results and normal values
- All operations are right-biased (operate on Right, short-circuit on Left)