OnCommand

@OnMessage(functionKind = FunctionKind.COMMAND, defaultFunctionName = "onCommand")
annotation class OnCommand(val returns: Array<KClass<*>> = [])

Marks a function as a command handler within an aggregate.

Functions annotated with @OnCommand are responsible for processing commands and producing domain events that represent state changes. They are the primary way aggregates respond to business operations.

Command handlers should:

  • Validate command data and business rules

  • Access and modify aggregate state

  • Return domain events representing the changes

  • Be idempotent when possible

  • Follow the command-query separation principle

Example usage:

@AggregateRoot
class OrderAggregate(
@AggregateId
val orderId: String
) {

@OnCommand(returns = [OrderCreated::class])
fun create(command: CreateOrderCommand): OrderCreated {
require(command.items.isNotEmpty()) { "Order must have items" }

return OrderCreated(
orderId = command.orderId,
customerId = command.customerId,
items = command.items,
total = calculateTotal(command.items)
)
}

@OnCommand
fun addItem(command: AddOrderItemCommand): OrderItemAdded {
// Business logic for adding items
return OrderItemAdded(command.orderId, command.item)
}
}

Parameters

returns

Array of event types that this handler may produce. Used for documentation and validation. Framework automatically infers return types when not specified.

See also

for aggregate classes containing command handlers

for event handlers

CommandAggregate

for the command processing implementation

Properties

Link copied to clipboard

Specifies the domain event types that this command handler may return.