Learning by Example

"For the things we have to learn before we can do them, we learn by doing them."

-- Aristotle, Nicomachean Ethics


The best way to understand functional programming in Java is to see it in action. This chapter presents a curated collection of runnable examples that demonstrate how to apply Higher-Kinded-J patterns to real problems.

Each example is complete and self-contained. You can run them, modify them, and use them as starting points for your own code. The examples progress from simple demonstrations of individual concepts to complete applications that show how the pieces fit together.

What You'll Find

  • Basic Examples – Core type demonstrations, from Maybe and Either to Monad Transformers
  • Effect Path API – Fluent composition of computations with error handling, validation, and resource management
  • Optics – Type-safe navigation and transformation of nested immutable data structures
  • Complete Applications – Production-quality examples showing how functional patterns solve real problems

Running Examples

All examples can be run using Gradle:

./gradlew :hkj-examples:run -PmainClass=<fully.qualified.ClassName>

For example:

./gradlew :hkj-examples:run -PmainClass=org.higherkindedj.example.basic.maybe.MaybeExample

Example Categories

Core Types

The foundation of functional programming: monadic types that represent different computational effects.

CategoryExamplesWhat You'll Learn
Optional ValuesMaybeExample, OptionalExampleSafe handling of missing values
Error HandlingEitherExample, TryExampleTyped errors and exception handling
ValidationValidatedMonadExampleAccumulating multiple errors
Side EffectsIOExample, LazyExampleDeferred and controlled execution
State & EnvironmentStateExample, ReaderExample, WriterExamplePure state threading and dependency injection
ConcurrencyCompletableFutureExample, VTaskPathExampleAsync operations and virtual threads

Monad Transformers

Combining multiple effects into unified stacks.

TransformerExampleWhat You'll Learn
EitherTEitherTExampleAsync operations with typed errors
MaybeTMaybeTExampleOptional values in effectful contexts
ReaderTReaderTExampleDependency injection with effects
StateTStateTExampleStateful computation within effects
WriterTWriterTExampleLogging and audit trails with effects

Effect Path API

Fluent, railway-oriented programming with composable effects.

CategoryExamplesWhat You'll Learn
Path BasicsBasicPathExample, ChainedComputationsExampleCreating paths, map/via, chaining
Error HandlingErrorHandlingExample, ServiceLayerExamplerecover, mapError, handleError
ValidationValidationPipelineExample, AccumulatingValidationExampleCombining validations, error accumulation
ForPathForPathExampleComprehension syntax for paths
ConcurrencyParallelExecutionExample, ScopeExampleParallel execution, structured concurrency
ResilienceResilienceExample, ResourceManagementExampleRetry policies, resource safety

Optics

Type-safe lenses, prisms, and traversals for immutable data.

CategoryExamplesWhat You'll Learn
Core OpticsLensUsageExample, PairedLensExample, PrismUsageExample, IsoUsageExample, AffineUsageExampleFundamental optic types
TraversalsTraversalUsageExample, FilteredTraversalExampleMultiple focus points, filtering
Focus DSLNavigatorExample, KindFieldFocusExample, TraverseIntegrationExample, ValidationPipelineExample, AsyncFetchExampleFluent navigation, validation, and async patterns
Fluent APIFluentApiExample, FreeDslExampleFluent optic operations, Free monad DSL
External TypesImportOpticsBasicExample, SpecInterfaceUsageExampleOptics for types you don't own
CookbookDeepUpdateRecipes, CollectionRecipesReady-to-use patterns

Context and Concurrency

Thread-safe context propagation with Java's ScopedValue API.

ExampleWhat You'll Learn
ContextBasicExampleBasic Context with ask, asks, map, flatMap
ContextScopeExampleContext with Scope for structured concurrency
RequestContextExampleRequest context propagation across layers
SecurityContextExampleAuthentication and authorization patterns
DistributedTracingExampleTracing across microservice boundaries

These complete applications demonstrate how functional patterns come together to solve real problems.

Order Processing Workflow

A production-quality e-commerce workflow demonstrating:

  • Typed error hierarchies with sealed interfaces
  • ForPath comprehensions for readable workflow composition
  • Resilience patterns: retries, timeouts, circuit breakers
  • Structured concurrency with VTask and Scope
  • Focus DSL for immutable state updates

Order Workflow Deep Dive →

Draughts (Checkers) Game

An interactive command-line game demonstrating:

  • Pure state management with WithStatePath
  • Railway-oriented validation using EitherPath
  • Side effect encapsulation with IOPath
  • Focus DSL for navigating game state
  • Stream-based patterns for declarative iteration

Draughts Game Deep Dive →

Market Data Pipeline

A virtual threads capstone demonstrating a complete concurrent data pipeline:

  • VStream.unfold for stateful stream generation
  • VStreamPar.merge for concurrent multi-exchange feed merging
  • Par.map2 and VStreamPar.parEvalMap for bounded parallel enrichment
  • VStream.chunk and flatMap for windowed aggregation and anomaly detection
  • Scope.allSucceed for multi-channel alert dispatch
  • CircuitBreaker and VStream.recoverWith for resilient feed failover

Market Data Pipeline Deep Dive →

Portfolio Risk Analysis

A cross-ecosystem navigation example demonstrating:

  • SPI type widening across JDK, Eclipse Collections, and HKJ container types
  • Path kind propagation through FocusPath, AffinePath, and TraversalPath
  • Navigator chains that cross three container ecosystems in a single expression
  • Affine optics for safe access to Either, Try, Validated, and Optional
  • TraversableGenerator SPI for automatic container recognition

Portfolio Risk Analysis Deep Dive →

Payment Processing

A comprehensive effect handlers example demonstrating:

  • Effect algebras with @EffectAlgebra for payment, fraud, ledger, and notification operations
  • Effect composition via @ComposeEffects and EitherF right-nesting
  • Four interpretation modes: production (IO), testing (Id), quote (fee estimation), and high-risk decline
  • Mock-free testing with pure Id monad interpreters
  • Program inspection with ProgramAnalyser before any side effects execute

Payment Processing Deep Dive →


Complete Examples Reference

For a comprehensive listing of all examples with run commands, see the Examples Guide in the repository.


Chapter Contents

  1. Order Processing Workflow – Building production-ready business workflows
  2. Draughts Game – Pure functional game development
  3. Market Data Pipeline – Virtual threads capstone with concurrent streaming
  4. Portfolio Risk Analysis – Cross-ecosystem container navigation with Focus DSL
  5. Payment Processing – Effect handlers with four interpretation modes

Next: Order Processing Workflow