Skip to content

Latest commit

 

History

History
111 lines (84 loc) · 3.09 KB

File metadata and controls

111 lines (84 loc) · 3.09 KB

Either - Java Implementation

Overview

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.

Project Structure

either/
├── src/main/java/stream/header/
│   └── Either.java          # Main Either implementation
├── pom.xml                  # Maven configuration
└── CLAUDE.md               # This file

Key Information

  • Language: Java 17+
  • Build Tool: Maven (use ./mvnw wrapper)
  • Package: stream.header
  • Main Class: Either<L, R> (sealed interface with Left and Right records)

Either API

Creation

Either<String, Integer> right = Either.right(42);
Either<String, Integer> left = Either.left("error");

Core Operations (Right-biased)

  • map(Function) - Transform Right value
  • flatMap(Function) - Chain Either-returning operations
  • mapLeft(Function) - Transform Left value
  • fold(Function, Function) - Pattern match on Left or Right
  • getOrElse(T) - Extract Right or default value
  • filterOrElse(Predicate, Supplier) - Filter Right value

Querying

  • isLeft() / isRight() - Check which side
  • contains(R) - Check if Right equals value
  • exists(Predicate) - Test Right value
  • getLeft() / getRight() - Unsafe extraction (throws if wrong side)

Conversion

  • toOptional() - Convert Right to Optional
  • toOptionalLeft() - Convert Left to Optional
  • swap() - Exchange Left and Right

Side Effects

  • forEach(Consumer) - Apply action to Right
  • forEachLeft(Consumer) - Apply action to Left

Build Commands

# Compile
./mvnw compile

# Run tests
./mvnw test

# Package
./mvnw package

# Clean
./mvnw clean

Design Decisions

  1. Sealed Interface: Uses Java 17 sealed interfaces for exhaustive pattern matching
  2. Records: Left and Right are immutable records
  3. Right-biased: All monadic operations (map, flatMap) operate on Right, matching modern Scala behavior
  4. Null Safety: Both Left and Right reject null values
  5. Fail-fast: Methods validate null parameters immediately

Usage Example

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"
    }
}

Conventions

  • 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)