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

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 →


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

Next: Order Processing Workflow