Skip to content

daggerok/fold-java

Repository files navigation

left fold GraalVM

Kotlin to the rescue

fold the universe: reduction with java 8 streams API

DomainEvents.kt

@file:JvmName("DomainEvents")

interface DomainEvent {
  val type: Class<out DomainEvent>
    get() = this.javaClass
}

class CounterCreatedEvent : DomainEvent
class CounterIncrementedEvent : DomainEvent
class CounterDecrementedEvent : DomainEvent

fun Aggregate.apply(event: DomainEvent): Aggregate = when (event) {
  is CounterCreatedEvent -> this.on(event)
  is CounterIncrementedEvent -> this.on(event)
  is CounterDecrementedEvent -> this.on(event)
  else -> throw IllegalStateException("unexpected unsupported domain event occur: $event")
}

Some.java

Optional<Aggregate> foldLeft(Aggregate initialState, DomainEvent... events) {
  if (events.length <= 0) return Optional.empty();
  Aggregate accumulator = initialState;
  for (DomainEvent event : events)
    accumulator = DomainEvents.apply(accumulator, event);
  return Optional.of(accumulator);
}

Run tests

./gradlew clean test

Links