🤔 When Is a DSL Worth Writing? Link to heading
Most Kotlin developers have used a DSL without writing one: Gradle’s build scripts, Ktor’s routing, Spring’s coRouter { }. They all feel the same. The code is shaped like the thing it builds.
Writing your own is less common, and for good reason. Plenty of DSLs are a builder with extra steps. Kotlin’s named arguments and default values already make most constructors readable.
A DSL earns its keep in two situations:
- The structure contains itself. A query made of queries. A menu made of menus. A state made of states. Built by hand, the shape of a nested structure gets buried under plumbing: constructors, lists, class references and a ladder of closing brackets. A DSL lets you write just the shape, the way you think about it, and check it as it’s built.
- One description gets used more than one way. You run it, you check it, you draw it, you test it. That only works if the description is data, and a DSL is a good way to write data that people can still read.
The example in this post has both. It’s long, because I want to show the whole thing: the model, the version without a DSL, the DSL version, and every line of the code that makes the DSL work.
The complete code is a small Gradle project, with tests, that you can download as a zip and run.
If you’re wondering why not Spring Statemachine: in April 2025, Spring announced it would stop maintaining it as open source, with 4.0.x as the last open-source line. Either way, the state machine here is the example, not the point.
🧾 The Example: A Subscription Lifecycle Link to heading
A paid subscription moves through a handful of states:
- It starts as a trial. When the trial ends, it becomes active.
- While active, it’s paid, past due after a failed payment (and while the retries keep failing), or paused at the customer’s request.
- The customer can cancel at any time, from any of those. A subscription whose payment retries run out is cancelled too.
- Once cancelled, nothing else happens to it.
Here’s how that usually looks in a codebase. Not in one place, but spread over a billing job, a controller and a webhook handler:
// BillingJob
if (sub.status == PAST_DUE && sub.failedAttempts >= 3) sub.status = CANCELLED
// SubscriptionController.cancel()
if (sub.status != CANCELLED) sub.status = CANCELLED
// PaymentWebhookHandler
when (event) {
is PaymentSucceeded -> sub.status = PAID // ...even if it was cancelled yesterday
is PaymentFailed -> sub.status = PAST_DUE
}
Each check is reasonable on its own. Together, nobody can see the whole lifecycle, and the bugs live in the gaps: a cancelled subscription that a late webhook marks as paid, or a paused one the billing job charges anyway.
Notice that “active” isn’t really a state. It’s a group of states: paid, past due and paused. Cancelling works the same from all three. That’s the nesting, and it’s what will make the DSL worth writing.
🧩 1) The Model Link to heading
Start with the domain: the statuses, and the events that move a subscription between them.
enum class Status { TRIAL, ACTIVE, PAID, PAST_DUE, PAUSED, CANCELLED }
sealed interface Event
data object TrialEnded : Event
data object PaymentSucceeded : Event
data class PaymentFailed(val attempt: Int) : Event
data object RetriesExhausted : Event
data object PauseRequested : Event
data object ResumeRequested : Event
data object CancelRequested : Event
Then the model of a state machine. It’s generic, so it doesn’t know about subscriptions, and it’s nothing but data classes:
data class Transition<S : Any, E : Any>(
val event: KClass<out E>,
val target: S,
)
data class StateNode<S : Any, E : Any>(
val state: S,
val transitions: List<Transition<S, E>> = emptyList(),
val children: List<StateNode<S, E>> = emptyList(),
val initial: S? = null,
val terminal: Boolean = false,
) {
fun withDescendants(): List<StateNode<S, E>> =
listOf(this) + children.flatMap { it.withDescendants() }
}
data class StateMachine<S : Any, E : Any>(
val initial: S,
val states: List<StateNode<S, E>>,
)
The line that matters is children: List<StateNode<S, E>>. A StateNode holds other StateNodes. A state with children has an initial child: entering ACTIVE really means entering PAID. A state with no children is where a subscription actually sits.
Running the machine takes one rule. When an event arrives, look for a transition on the current state first, then on its parent, then on its grandparent. That’s how a CancelRequested declared once on ACTIVE applies to PAID, PAST_DUE and PAUSED:
val <S : Any, E : Any> StateMachine<S, E>.start: S
get() = enter(initial)
fun <S : Any, E : Any> StateMachine<S, E>.next(current: S, event: E): S {
val path = states.pathTo(current) ?: error("Unknown state $current")
val transition = path.asReversed().firstNotNullOfOrNull { node ->
node.transitions.firstOrNull { it.event.isInstance(event) }
} ?: error("$current doesn't accept ${event::class.simpleName}")
return enter(transition.target)
}
private fun <S : Any, E : Any> StateMachine<S, E>.enter(state: S): S {
val node = states.pathTo(state)?.last() ?: error("Unknown state $state")
return node.initial?.let { enter(it) } ?: state
}
private fun <S : Any, E : Any> List<StateNode<S, E>>.pathTo(state: S): List<StateNode<S, E>>? {
for (node in this) {
if (node.state == state) return listOf(node)
node.children.pathTo(state)?.let { return listOf(node) + it }
}
return null
}
An event the current state doesn’t accept is an error, not a quiet no-op. That’s the late webhook from earlier: a cancelled subscription can’t be marked paid, because CANCELLED has no transitions at all.
None of this needs a DSL yet. The DSL is only about how you build a StateMachine.
🧱 2) Building It Without a DSL Link to heading
How painful that is depends on the language. Java first, because that’s where most of our habits come from.
📦 In Java: one variable per node Link to heading
Here’s the model as Java records:
record Transition<S, E>(Class<? extends E> event, S target) {}
record StateNode<S, E>(S state, List<Transition<S, E>> transitions,
List<StateNode<S, E>> children, S initial, boolean terminal) {}
record StateMachine<S, E>(S initial, List<StateNode<S, E>> states) {}
A record has one constructor, and its arguments are positional. Nest those calls and you’re counting commas to tell a state from an initial. So Java code names each node and builds the leaves first:
var paid = new StateNode<Status, Event>(PAID,
List.of(new Transition<>(PaymentFailed.class, PAST_DUE),
new Transition<>(PauseRequested.class, PAUSED)),
List.of(), null, false);
var pastDue = new StateNode<Status, Event>(PAST_DUE,
List.of(new Transition<>(PaymentSucceeded.class, PAID),
new Transition<>(PaymentFailed.class, PAST_DUE)),
List.of(), null, false);
var paused = new StateNode<Status, Event>(PAUSED,
List.of(new Transition<>(ResumeRequested.class, PAID)),
List.of(), null, false);
var active = new StateNode<Status, Event>(ACTIVE,
List.of(new Transition<>(CancelRequested.class, CANCELLED),
new Transition<>(RetriesExhausted.class, CANCELLED)),
List.of(paid, pastDue, paused), PAID, false);
var trial = new StateNode<Status, Event>(TRIAL,
List.of(new Transition<>(TrialEnded.class, ACTIVE),
new Transition<>(CancelRequested.class, CANCELLED)),
List.of(), null, false);
var cancelled = new StateNode<Status, Event>(CANCELLED, List.of(), List.of(), null, true);
var subscription = new StateMachine<>(TRIAL, List.of(trial, active, cancelled));
That style has a cost:
- It reads bottom up. You meet
PAIDbefore you know it lives insideACTIVE. The lifecycle starts withTRIAL, which shows up near the end. - The structure is in the variable names.
ACTIVEholdsPAIDbecauseList.of(paid, pastDue, paused)says so. Indentation tells you nothing. - Noise.
List.of(), null, falseon every leaf,<Status, Event>on every node,.classon every event.
A builder per record is the usual Java fix: method names instead of positions, and builders you can nest. Kotlin gets there with no extra code.
📐 In Kotlin: nested, with named arguments Link to heading
Kotlin’s named arguments and default values take care of most of that. You can nest the constructor calls and still see what each argument is, so the code can follow the shape:
val handBuilt = StateMachine<Status, Event>(
initial = TRIAL,
states = listOf(
StateNode(
state = TRIAL,
transitions = listOf(
Transition(TrialEnded::class, ACTIVE),
Transition(CancelRequested::class, CANCELLED),
),
),
StateNode(
state = ACTIVE,
initial = PAID,
transitions = listOf(
Transition(CancelRequested::class, CANCELLED),
Transition(RetriesExhausted::class, CANCELLED),
),
children = listOf(
StateNode(
state = PAID,
transitions = listOf(
Transition(PaymentFailed::class, PAST_DUE),
Transition(PauseRequested::class, PAUSED),
),
),
StateNode(
state = PAST_DUE,
transitions = listOf(
Transition(PaymentSucceeded::class, PAID),
Transition(PaymentFailed::class, PAST_DUE),
),
),
StateNode(
state = PAUSED,
transitions = listOf(Transition(ResumeRequested::class, PAID)),
),
),
),
StateNode(CANCELLED, terminal = true),
),
)
That’s a fair fight. It reads top down, PAID sits inside ACTIVE, and the indentation is the structure. If your structure is this size and rarely changes, you can stop here. Named arguments are often enough.
What’s left is this:
- Plumbing.
StateNode(,transitions = listOf(,Transition(and::class, over and over, then a ladder of closing brackets. The rules are in there, but you have to dig for them. - Nothing checks the rules. Delete the
PAUSEDnode and it still compiles and starts.PAIDstill points atPAUSED, which no longer exists. You find out when the first customer pauses:Unknown state PAUSED.
Every extra level of nesting adds more plumbing. Our lifecycle has two levels. A real one might have three or four.
✨ 3) The Same Machine as a DSL Link to heading
Here’s the same lifecycle, written with the DSL we’re about to build:
val subscription = stateMachine<Status, Event>(initial = TRIAL) {
state(TRIAL) {
on<TrialEnded> { goTo(ACTIVE) }
on<CancelRequested> { goTo(CANCELLED) }
}
state(ACTIVE, initial = PAID) {
on<CancelRequested> { goTo(CANCELLED) }
on<RetriesExhausted> { goTo(CANCELLED) }
state(PAID) {
on<PaymentFailed> { goTo(PAST_DUE) }
on<PauseRequested> { goTo(PAUSED) }
}
state(PAST_DUE) {
on<PaymentSucceeded> { goTo(PAID) }
on<PaymentFailed> { goTo(PAST_DUE) }
}
state(PAUSED) {
on<ResumeRequested> { goTo(PAID) }
}
}
terminal(CANCELLED)
}
The shape is the same as the nested constructors: top down, with the indentation as the structure. What’s gone is the plumbing. There’s no listOf, no Transition(, no ::class and no ladder of brackets, so each line reads as a rule: on TrialEnded, go to ACTIVE. Both ways out of ACTIVE are declared once, on ACTIVE, and the three states inside it inherit them.
It also builds exactly the same object. The model is data classes, so this is a real equality check:
println(handBuilt == subscription) // true
That’s a useful trick for testing your own DSL. Build one thing both ways, and compare.
Running it shows the nesting at work:
start: TRIAL
TRIAL --TrialEnded--> PAID
PAID --PaymentFailed--> PAST_DUE
PAST_DUE --PaymentFailed--> PAST_DUE
PAST_DUE --PaymentSucceeded--> PAID
PAID --PauseRequested--> PAUSED
PAUSED --CancelRequested--> CANCELLED
rejected: CANCELLED doesn't accept PaymentSucceeded
TrialEnded goes to ACTIVE, which enters PAID. A second failed payment keeps it past due. PAUSED has no CancelRequested of its own, so it uses ACTIVE’s. And the late payment on a cancelled subscription is rejected.
🔧 4) How the DSL Works Link to heading
The whole DSL is about 75 lines. Four ideas carry it.
🧷 1) Lambdas with receivers Link to heading
The entry point takes a lambda whose receiver is a builder:
fun <S : Any, E : Any> stateMachine(
initial: S,
block: MachineBuilder<S, E>.() -> Unit,
): StateMachine<S, E> = MachineBuilder<S, E>(initial).apply(block).build()
MachineBuilder<S, E>.() -> Unit is a lambda with a receiver. Inside the braces, this is a MachineBuilder, so state(...) and terminal(...) are calls on that builder. apply(block) runs the lambda against a fresh builder, then build() turns what it collected into the immutable model. (If apply is fuzzy, I wrote about when to use apply, let, also and run.)
Every builder in the DSL follows the same three steps: create a builder, apply the block, build(). Builders are mutable and short-lived. The model they produce is immutable.
🪆 2) A builder that contains itself Link to heading
The model nests because StateNode holds StateNodes. The DSL nests the same way, because the builder for a state can declare more states:
@DslMarker
annotation class LifecycleDsl
@LifecycleDsl
abstract class StatesBuilder<S : Any, E : Any> {
protected val children = mutableListOf<StateNode<S, E>>()
fun state(state: S, initial: S? = null, block: StateBuilder<S, E>.() -> Unit = {}) {
children += StateBuilder<S, E>(state, initial).apply(block).build()
}
fun terminal(state: S) {
children += StateNode(state, terminal = true)
}
}
StatesBuilder is anything that can hold states. The machine is one: MachineBuilder extends it. And a state is one too, because StateBuilder extends it as well:
class StateBuilder<S : Any, E : Any>(
private val state: S,
private val initial: S?,
) : StatesBuilder<S, E>() {
private val transitions = mutableListOf<Transition<S, E>>()
inline fun <reified T : E> on(block: TransitionBuilder<S>.() -> Unit) {
addTransition(T::class, TransitionBuilder<S>().apply(block).build())
}
@PublishedApi
internal fun addTransition(event: KClass<out E>, target: S) {
transitions += Transition(event, target)
}
fun build(): StateNode<S, E> {
if (children.isNotEmpty()) {
requireNotNull(initial) { "$state has sub-states, so it needs an initial one" }
}
if (initial != null) {
require(children.any { it.state == initial }) { "$initial isn't a sub-state of $state" }
}
return StateNode(state, transitions.toList(), children.toList(), initial)
}
}
So inside state(ACTIVE) { ... }, state(PAID) { ... } is just another call to the same state function, on a different builder. That’s the whole trick to a nested DSL: the builder for a thing can build more of the same thing. Two levels or ten, nothing changes.
🏷️ 3) on<PaymentFailed>: reified type parameters
Link to heading
on<PaymentFailed> { ... } reads better than on(PaymentFailed::class) { ... }. To get it, on takes a reified type parameter, which lets the function body use T::class. Only inline functions can have one.
That has a knock-on effect. A public inline function’s body is copied into its callers, which can be in other modules, so it can’t use private or internal members. Marking an internal member @PublishedApi lifts that for it, which is what addTransition is for. You’ll hit this in almost every DSL that uses reified types.
The last builder is the smallest. It exists so a transition reads as a sentence, and so a forgotten goTo fails loudly:
@LifecycleDsl
class TransitionBuilder<S : Any> {
private var target: S? = null
fun goTo(state: S) {
target = state
}
fun build(): S = checkNotNull(target) { "every on<...> needs a goTo(...)" }
}
✅ 4) Check what the types can’t Link to heading
The types stop a lot of mistakes. goTo("PAID") won’t compile, and neither will on<String>. Some rules span the whole tree, though, and the place to check them is build(). The machine’s builder checks them all, once, when the definition is built:
class MachineBuilder<S : Any, E : Any>(private val initial: S) : StatesBuilder<S, E>() {
fun build(): StateMachine<S, E> {
val nodes = children.flatMap { it.withDescendants() }
val declared = nodes.map { it.state }
val duplicates = declared.groupingBy { it }.eachCount().filterValues { it > 1 }.keys
require(duplicates.isEmpty()) { "Declared more than once: $duplicates" }
require(initial in declared) { "The initial state $initial isn't declared" }
val undeclared = nodes.flatMap { it.transitions }.map { it.target }.filterNot { it in declared }
require(undeclared.isEmpty()) { "goTo(...) targets that aren't declared: $undeclared" }
return StateMachine(initial, children.toList())
}
}
Remember deleting PAUSED from the hand-built version? It started fine and failed on the first pause. Leave out state(PAUSED) in the DSL version and it fails as soon as the definition is built:
goTo(...) targets that aren't declared: [PAUSED]
So build it once, when the application starts, and in a unit test. That’s the cheapest possible place to fail. One catch: a top-level val like subscription is built the first time something uses it, not at startup, so make it a Spring @Bean or touch it in main.
🧯 The Bug @DslMarker Stops
Link to heading
There’s one line I skipped: @DslMarker on the LifecycleDsl annotation, and @LifecycleDsl on the builders. Here’s why it’s there.
Inside a lambda with a receiver, Kotlin can also see the receivers of every lambda around it. Inside on<RetriesExhausted> { ... }, the closest receiver is a TransitionBuilder. But the StateBuilder for ACTIVE is still in scope, and so is the MachineBuilder. If you call something the TransitionBuilder doesn’t have, Kotlin quietly calls it on an outer builder.
Here’s a mistake that looks perfectly reasonable:
state(ACTIVE, initial = PAID) {
on<RetriesExhausted> {
goTo(CANCELLED)
terminal(CANCELLED) // "and that's the end of it"
}
state(PAID)
}
terminal(CANCELLED)
Without @DslMarker, this compiles. TransitionBuilder has no terminal, so the call goes to the nearest builder that does: the StateBuilder for ACTIVE. CANCELLED is now declared twice, once inside ACTIVE and once at the top. The only thing that catches it is the duplicate check, when the definition is built:
Declared more than once: [CANCELLED]
With @DslMarker, it doesn’t compile:
error: 'fun terminal(state: Status): Unit' cannot be called in this context with an implicit receiver. Use an explicit receiver if necessary.
The rule: inside a lambda whose receiver carries a marker, you can’t implicitly call outer receivers that carry the same marker. You can still reach them on purpose, with a label. this@state names the nearest state { } lambda, which is fine one level down. Two levels down it’s ambiguous: inside state(PAID), this@state means PAID, and the compiler only warns. So give the outer lambda its own label, as in state(ACTIVE, initial = PAID) active@{ ... }, and write this@active. You can reach any builder on purpose. You just can’t reach one by accident.
Putting the annotation on the abstract StatesBuilder covers both StateBuilder and MachineBuilder, because the marker counts for a receiver if its class or any of its supertypes has it. In a nested DSL, where every level offers the same functions, this is the one annotation you can’t skip.
🖼️ 5) A Second Output, Almost for Free Link to heading
The definition is data, so you can do more with it than run it. Here’s a renderer that turns any StateMachine into a Mermaid diagram. It’s recursive, like everything else here:
fun <S : Any, E : Any> StateMachine<S, E>.toMermaid(): String = buildString {
appendLine("stateDiagram-v2")
appendLine(" [*] --> $initial")
states.forEach { appendNode(it, indent = " ") }
}
private fun <S : Any, E : Any> StringBuilder.appendNode(node: StateNode<S, E>, indent: String) {
if (node.children.isNotEmpty()) {
appendLine("${indent}state ${node.state} {")
appendLine("$indent [*] --> ${node.initial}")
node.children.forEach { appendNode(it, "$indent ") }
appendLine("$indent}")
}
node.transitions.forEach {
appendLine("$indent${node.state} --> ${it.target} : ${it.event.simpleName}")
}
if (node.terminal) appendLine("$indent${node.state} --> [*]")
}
For the subscription, it prints:
stateDiagram-v2
[*] --> TRIAL
TRIAL --> ACTIVE : TrialEnded
TRIAL --> CANCELLED : CancelRequested
state ACTIVE {
[*] --> PAID
PAID --> PAST_DUE : PaymentFailed
PAID --> PAUSED : PauseRequested
PAST_DUE --> PAID : PaymentSucceeded
PAST_DUE --> PAST_DUE : PaymentFailed
PAUSED --> PAID : ResumeRequested
}
ACTIVE --> CANCELLED : CancelRequested
ACTIVE --> CANCELLED : RetriesExhausted
CANCELLED --> [*]
Put that in a Markdown file inside a mermaid code block, and GitHub draws it. Generate it in a test and commit it, and your docs can’t drift from your code, because they are your code.
To be fair to the nested constructors: they build the same object, so they render too. The renderer works because the DSL builds plain data. That’s the real lesson, and it’s easy to lose.
🧭 Keep It Data, Not Code Link to heading
Kotlin lets you put any code inside a DSL’s lambdas. That’s a strength. You can use an if to leave a state out, or a loop to declare a set of similar states, and the result is still plain data.
But notice what on<PaymentFailed> { ... } isn’t. It isn’t an event handler. The lambda runs once, when the machine is built, and all it does is record a target. There’s no it.attempt in there to branch on.
That’s deliberate. The tempting design is a handler:
on<PaymentFailed> { event -> if (event.attempt >= 3) CANCELLED else PAST_DUE }
It’s more flexible, and it quietly gives up everything this post has been working toward. The renderer can’t draw an if. The build checks can’t see where it goes. A reader has to run the code in their head again.
So this machine has a RetriesExhausted event instead. The billing job, which knows the retry policy, decides when retries have run out. The lifecycle only records what happens next. When your DSL starts growing lambdas that make decisions, ask whether the decision belongs in an event instead.
✅ A Checklist for Your Own DSL Link to heading
Reach for a DSL when:
- The structure nests: things made of things like themselves
- It’s read more often than it’s written, by people who didn’t write it
- The same definition is used more than one way: run, checked, drawn, tested
- There are rules you can check once, when it’s built
Skip it when the structure is flat, there’s one call site, or named arguments already read well.
When you build one:
- Keep builders separate from the model. Builders are mutable; the model is immutable data
- One
@DslMarkerannotation, on every builder (or a shared base class) - Check what the types can’t in
build(), with messages that name the problem - Test it by building the same thing by hand and comparing with
== - Keep the lambdas declarative. Decisions belong in events and data, not hidden in the DSL
☕ Conclusion Link to heading
A DSL makes a structure readable to the next person, and checkable by the compiler and by build(). When the structure nests, the difference adds up. Java pushes you to build it inside out. Kotlin’s named arguments get you top down, but leave the plumbing and check nothing. A DSL leaves just the shape and the rules, and checks them.
The building blocks are small. Lambdas with receivers, a builder that can contain itself, a reified type here and there, and one @DslMarker you shouldn’t skip. Keep what it builds as plain data, and you get more than readability: a diagram, a set of checks, and tests, from one definition.
The point isn’t cleverness. The point is code that’s easy to understand and to maintain. Say the model changes: the final state is now TERMINATED rather than CANCELLED, and a cancelled subscription can be uncancelled. Which code would you want to change?
Sources
- The complete code for this post: a Gradle project with tests (zip)
- Kotlin docs: Type-safe builders (including scope control with
@DslMarker) - Kotlin API:
DslMarker - Kotlin docs: Function literals with receiver
- Kotlin docs: Inline functions and reified type parameters
- Kotlin API:
PublishedApi - Mermaid: State diagrams (composite states)
- GitHub Docs: Creating Mermaid diagrams
- Spring: Spring Cloud Data Flow, Spring Cloud Deployer and Spring Statemachine end of open source (2025)
- David Harel, “Statecharts: A visual formalism for complex systems” (1987), where nested states come from
Related Posts