Skip to content

Kotlin

The actor-kotlin module adds a thin Kotlin layer over the Java API: a behavior { } DSL for actor behaviors, suspend functions instead of CompletionStage, reified type parameters instead of Class arguments, and kotlin.time.Duration timeouts. Each function calls the Java API, so everything in the other guides applies unchanged.

Incubating

actor-kotlin is incubating: its API may still change in a minor release, without a deprecation period, while it collects feedback. The compatibility promise covers the core and cluster API.

Installation

Add actor-kotlin next to the starter. It brings kotlinx-coroutines-core; Spring Boot manages its version.

dependencies {
    implementation("io.github.seonwkim:actor-spring-boot-starter:1.1.0")
    implementation("io.github.seonwkim:actor-kotlin:1.1.0")
}

The module is compiled with Kotlin 1.9.25, the version Spring Boot 3.5 manages, so applications on that version or later can use it.

Null safety

actor-api declares its nullability: values are non-null unless marked @Nullable (for example AskCommand.getReplyTo()). Kotlin turns those annotations into Kotlin types with the -Xjsr305=strict compiler flag, which projects generated by start.spring.io already set:

kotlin {
    compilerOptions {
        freeCompilerArgs.addAll("-Xjsr305=strict")
    }
}

Without the flag, Kotlin only warns, and the API's types are platform types (String!).

Defining an actor

behavior<Command>(actorContext) { ... } builds the behavior with SpringActorBehavior.builder. Commands are often a sealed interface:

@Component
class HelloActor : SpringActor<HelloActor.Command> {
    sealed interface Command

    class SayHello : AskCommand<String>(), Command

    data class LogVisit(val name: String) : Command

    override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
        behavior<Command>(actorContext) {
            onMessage<SayHello> { msg ->
                msg.reply("Hello from actor ${actorContext.actorId()}")
                same()
            }
            onMessage<LogVisit> { msg ->
                log.info("{} visited", msg.name)   // the behavior context is `this`
                same()
            }
        }
}

Inside the block:

DSL Java builder
onMessage<M> { msg -> next } .onMessage(M.class, (ctx, msg) -> next)
onSignal<PostStop> { signal -> next } .onSignal(PostStop.class, (ctx, signal) -> next)
withSupervisionStrategy(strategy) .withSupervisionStrategy(strategy)
withMdc { msg -> mapOf(...) } .withMdc(msg -> Map.of(...))
same(), stopped(), unhandled() SpringActorBehavior.same(), .stopped(), .unhandled()

A handler runs with the behavior context as this, so self, log, pipeToSelf(...), watch(...) and the timers need no ctx. prefix. It returns the next behavior: same(), stopped(), unhandled(), or another behavior { } to switch behaviors.

State

To keep state in an object, pass a state factory (withState). It runs when the actor starts and again on each restart, and the handlers then run with the state object as this:

override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
    behavior<Command, Counter>(actorContext, state = { ctx -> Counter(ctx) }) {
        onMessage<Add> { msg -> onAdd(msg) }
        onMessage<Get> { msg -> onGet(msg) }
    }

behavior<Command, _> works too: Kotlin infers the state type from the factory.

actorBehavior<Command>(actorContext) returns the Java builder itself, for code that prefers the chained .onMessage(Type::class.java) { ctx, msg -> ... }.build() style.

Spawning and finding actors

The reified helpers take the actor type as a type argument. Kotlin can't infer the command type from the actor type by itself, so pass _ for it:

// actorSystem.actor(HelloActor::class.java)
val builder = actorSystem.actor<HelloActor, _>()

// Suspends until the actor runs
val hello: SpringActorHandle<HelloActor.Command> =
    actorSystem.actor<HelloActor, _>().withId("hello").withTimeout(5.seconds).awaitSpawn()

val running = actorSystem.awaitGetOrSpawn<HelloActor, _>("hello") // spawn when none runs
val maybe = actorSystem.awaitGet<HelloActor, _>("hello")          // null when none runs
val exists = actorSystem.awaitExists<HelloActor, _>("hello")

// Sharded actors (cluster mode)
val counter = actorSystem.sharded<CounterActor, _>().withId("counter-1").get()
Kotlin Java API it calls
actor<A, _>() actor(A.class)
sharded<A, _>() sharded(A.class)
awaitGetOrSpawn<A, _>(id), awaitGet<A, _>(id), awaitExists<A, _>(id) getOrSpawn, find (as a nullable), exists with A.class
builder.awaitSpawn(), builder.awaitGetOrSpawn() spawn(), getOrSpawn() on the spawn builder
behavior<C>(actorContext) { }, behavior<C, S>(actorContext, state = { ctx -> S(ctx) }) { } SpringActorBehavior.builder(C.class, actorContext), then withState, the handlers and build()
actorBehavior<C>(actorContext) SpringActorBehavior.builder(C.class, actorContext)
handle.child<A, _>(), handle.child<A, _>(id) child(A.class), child(A.class, id)
awaitSpawn(), awaitGetOrSpawn(), awaitExists() on a child builder; awaitGet(), awaitExists() on a child reference spawn(), getOrSpawn(), get(), exists()
withTimeout(5.seconds), withLimit(10, 1.minutes), startSingleTimer(key, msg, 30.seconds), startTimerAtFixedRate(key, msg, 10.seconds) the same methods with a java.time.Duration
unwrap<X>() on the actor system, a ref or a behavior context unwrap(X.class)

Child actors

handle.child<A, _>() is the child builder and handle.child<A, _>(id) the lookup reference of Child actors. Outside the parent, the await* functions suspend until the operation completes. A child lookup returns null when the child doesn't run:

// In a suspend function, with the parent's handle
val worker = dispatcher.child<WorkerActor, _>()
    .withId("worker-1")
    .withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes))
    .withTimeout(5.seconds)
    .awaitGetOrSpawn()

val found: SpringActorHandle<WorkerActor.Command>? = dispatcher.child<WorkerActor, _>("worker-1").awaitGet()
val running: Boolean = dispatcher.child<WorkerActor, _>("worker-1").awaitExists()

Inside the parent's own handlers, don't wait: pass spawn() or getOrSpawn() to pipeToSelf, as in Spawning children from inside the parent.

Durations

These methods also take a kotlin.time.Duration: withTimeout on the spawn, sharded, child and ask builders and on the child reference, SupervisionStrategy.restart().withLimit, and the timers on the behavior context:

ctx.startSingleTimer("idle", IdleTimeout, 30.minutes)
ctx.startTimerAtFixedRate("flush", Flush, 10.seconds)

Asking

awaitAsk sends an AskCommand and suspends until the reply arrives. Without a timeout, the handle's default timeout (3 seconds) applies.

val greeting: String = hello.awaitAsk(HelloActor.SayHello(), timeout = 2.seconds)

When no reply arrives in time, awaitAsk throws java.util.concurrent.TimeoutException. For a fallback value instead, use the ask builder and finish it with await():

val greeting = hello.ask(HelloActor.SayHello())
    .withTimeout(2.seconds)
    .onTimeout { "no answer" }
    .await()

awaitAsk works the same on a sharded actor handle. Cancelling the coroutine stops the wait; the command has already been sent.

In a WebFlux controller

With kotlinx-coroutines-reactor and kotlin-reflect on the classpath, WebFlux runs suspend handler functions:

@RestController
class HelloController(private val actorSystem: SpringActorSystem) {
    @GetMapping("/hello")
    suspend fun hello(): String =
        actorSystem.awaitGetOrSpawn<HelloActor, _>("hello-actor")
            .awaitAsk(HelloActor.SayHello(), timeout = 3.seconds)
}

The full application is in example/kotlin: the simple example, written in Kotlin. The Kotlin example page walks through it.