Design patterns

suggest change

The classic "Gang of Four" design patterns were described for C++ and Smalltalk, and most of them became famous in Java, where they need a lot of boilerplate. Kotlin has language features that make many patterns either disappear or shrink to a few lines:

Pattern Kotlin feature
Singleton object declaration
Factory method companion object functions, top-level functions, sealed types
Builder named and default arguments, copy(), lambdas with receiver
Strategy, Command, Template method function types and lambdas, fun interface
Decorator, Proxy class delegation with by, delegated properties, lazy
Observer function listeners, StateFlow / Flow
State, Visitor sealed classes with exhaustive when
Adapter extension functions
Iterator sequence { } and iterator { } builders
Chain of responsibility a list of functions combined with fold

This article shows the idiomatic Kotlin version of each one. A few patterns have their own articles in this book, so they're only briefly mentioned here:

Singleton

In Kotlin a singleton is an object declaration. It's created lazily and thread-safely on first access, and it can implement interfaces and extend classes:

object Registry {
    private val items = mutableMapOf<String, Int>()
    fun register(name: String, value: Int) { items[name] = value }
}

There's no need for a private constructor, a static getInstance() or double-checked locking. See singleton objects for details. A word of warning: a global singleton that holds state makes code hard to test. Prefer passing dependencies in, as described in dependency injection.

Factory method

A factory creates objects without the caller knowing the exact class. Kotlin has no static methods, so factories go into a companion object. Combined with a sealed interface, the factory can return one of a closed set of implementations:

sealed interface Shape {
    val area: Double

    data class Circle(val r: Double) : Shape {
        override val area get() = Math.PI * r * r
    }
    data class Rect(val w: Double, val h: Double) : Shape {
        override val area get() = w * h
    }

    companion object {
        fun parse(spec: String): Shape {
            val parts = spec.split(" ")
            val nums = parts.drop(1).map { it.toDouble() }
            return when (parts[0]) {
                "circle" -> Circle(nums[0])
                "rect" -> Rect(nums[0], nums[1])
                "square" -> Rect(nums[0], nums[0])
                else -> throw IllegalArgumentException("unknown shape: ${parts[0]}")
            }
        }
    }
}

fun main() {
    for (spec in listOf("circle 1", "rect 2 3", "square 4")) {
        val s = Shape.parse(spec)
        println("$s area=${"%.2f".format(s.area)}")
    }
    runCatching { Shape.parse("hexagon 1") }.onFailure { println(it.message) }
}
Circle(r=1.0) area=3.14
Rect(w=2.0, h=3.0) area=6.00
Rect(w=4.0, h=4.0) area=16.00
unknown shape: hexagon

Two other common factory styles:

class Temperature private constructor(val kelvin: Double) {
    companion object {
        fun ofCelsius(c: Double) = Temperature(c + 273.15)
        fun ofFahrenheit(f: Double) = Temperature((f - 32) * 5 / 9 + 273.15)
    }
    override fun toString() = "%.2f K".format(kelvin)
}

interface Cache {
    fun get(key: String): String?
    fun put(key: String, value: String)
}

private class MapCache : Cache {
    private val m = HashMap<String, String>()
    override fun get(key: String) = m[key]
    override fun put(key: String, value: String) { m[key] = value }
}

// a factory function named like the interface
fun Cache(): Cache = MapCache()

fun main() {
    println(Temperature.ofCelsius(100.0))
    println(Temperature.ofFahrenheit(32.0))
    // Temperature(5.0) // error: cannot access constructor: it is private

    val cache = Cache()
    cache.put("a", "1")
    println("${cache.get("a")} ${cache::class.simpleName}")
}
373.15 K
273.15 K
1 MapCache

Because MapCache is private, callers can only see the Cache interface, and you're free to replace the implementation later.

You can also make a factory look like a constructor call by defining operator fun invoke in a companion object, but a plain named function is usually clearer.

Builder

In Java a builder exists mainly because Java has no named or default arguments. In Kotlin, a class with default parameter values already behaves like a builder, and copy() on a data class gives you "a copy with one thing changed":

data class HttpRequest(
    val url: String,
    val method: String = "GET",
    val headers: Map<String, String> = emptyMap(),
    val body: String? = null,
    val timeoutMs: Long = 30_000,
)

fun main() {
    val get = HttpRequest("https://example.com")
    val post = HttpRequest(
        url = "https://example.com/users",
        method = "POST",
        headers = mapOf("Content-Type" to "application/json"),
        body = """{"name":"Ann"}""",
    )
    val slow = post.copy(timeoutMs = 120_000)
    println(get)
    println(post)
    println(slow.timeoutMs)
}
HttpRequest(url=https://example.com, method=GET, headers={}, body=null, timeoutMs=30000)
HttpRequest(url=https://example.com/users, method=POST, headers={Content-Type=application/json}, body={"name":"Ann"}, timeoutMs=30000)
120000

That covers 90% of the cases where Java would use a builder. A real builder is still useful when:

The idiomatic way is a mutable Builder class plus a function taking a lambda with receiver (Builder.() -> Unit). Inside the lambda, this is the builder, so you call its methods directly:

class Query private constructor(
    val table: String,
    val columns: List<String>,
    val where: List<String>,
    val limit: Int?,
) {
    class Builder(private val table: String) {
        private val columns = mutableListOf<String>()
        private val where = mutableListOf<String>()
        private var limit: Int? = null

        fun select(vararg cols: String) { columns += cols }
        fun where(cond: String) { where += cond }
        fun limit(n: Int) {
            require(n > 0) { "limit must be positive" }
            limit = n
        }

        fun build(): Query {
            check(columns.isNotEmpty()) { "select at least one column" }
            return Query(table, columns.toList(), where.toList(), limit)
        }
    }

    override fun toString() = buildString {
        append("SELECT ${columns.joinToString()} FROM $table")
        if (where.isNotEmpty()) append(" WHERE ${where.joinToString(" AND ")}")
        limit?.let { append(" LIMIT $it") }
    }
}

fun query(table: String, block: Query.Builder.() -> Unit): Query =
    Query.Builder(table).apply(block).build()

fun main() {
    val q = query("users") {
        select("id", "name")
        where("age > 18")
        where("active = true")
        limit(10)
    }
    println(q)

    val dynamic = query("orders") {
        select("*")
        if (System.getenv("ONLY_RECENT") != null) where("created > now() - 1")
    }
    println(dynamic)

    runCatching { query("users") { } }.onFailure { println(it.message) }
}
SELECT id, name FROM users WHERE age > 18 AND active = true LIMIT 10
SELECT * FROM orders
select at least one column

The Query constructor is private, so the only way to get a Query is through the builder, which guarantees that build() checks ran. The standard library uses the same pattern in buildString, buildList, buildMap and buildSet. For nested builders like HTML, see type-safe builders; for apply-based configuration see use apply to initialize objects.

Strategy

Strategy means passing an algorithm as a parameter. In Java this is an interface with one method and a class per algorithm. In Kotlin it's a function type:

data class Item(val name: String, val price: Double)

typealias Discount = (Double) -> Double

val noDiscount: Discount = { it }
fun percentOff(p: Int): Discount = { it * (100 - p) / 100 }
fun amountOff(a: Double): Discount = { maxOf(0.0, it - a) }

class Checkout(private val discount: Discount = noDiscount) {
    fun total(items: List<Item>): Double = discount(items.sumOf { it.price })
}

fun main() {
    val cart = listOf(Item("book", 30.0), Item("pen", 5.0))
    println(Checkout().total(cart))
    println(Checkout(percentOff(20)).total(cart))
    println(Checkout(amountOff(10.0)).total(cart))
    println(Checkout { if (it > 20) it - 5 else it }.total(cart))

    // the standard library is full of strategies
    val byPrice = cart.sortedWith(compareByDescending<Item> { it.price }.thenBy { it.name })
    println(byPrice.map { it.name })
}
35.0
28.0
25.0
30.0
[book, pen]

A typealias gives the function type a meaningful name (see function type). Strategies are created by plain functions like percentOff(20) that return lambdas, and the caller can pass an ad-hoc lambda without defining anything. The standard library is built around this: sortedWith(comparator), groupBy(keySelector), filter(predicate) and Regex.replace(input, transform) all take a strategy.

If you want a named type that shows up in signatures and can have extra methods, use a fun interface. It can still be created from a lambda:

fun interface Validator {
    fun validate(value: String): String?   // error message or null

    infix fun and(other: Validator) = Validator { v -> validate(v) ?: other.validate(v) }
}

val notBlank = Validator { if (it.isBlank()) "must not be blank" else null }
fun maxLen(n: Int) = Validator { if (it.length > n) "longer than $n" else null }
val ascii = Validator { if (it.all { c -> c.code < 128 }) null else "non-ASCII" }

fun main() {
    val username = notBlank and maxLen(8) and ascii
    for (s in listOf("ann", "", "verylongname", "zoë")) {
        println("'$s' -> ${username.validate(s) ?: "ok"}")
    }
}
'ann' -> ok
'' -> must not be blank
'verylongname' -> longer than 8
'zoë' -> non-ASCII

The and method composes validators, which gets awkward with plain function types.

Template method

The template method pattern defines the skeleton of an algorithm in a base class and lets subclasses fill in the steps through abstract and open methods. Kotlin supports that classic version (remember that classes and methods are final by default, see the open keyword), but often you don't need inheritance at all. A higher-order function is a template where the "step" is a lambda. The fixed parts (timing, retrying, opening and closing resources, transactions) live in the function, and the variable part is passed in:

inline fun <T> timed(name: String, block: () -> T): T {
    val start = System.nanoTime()
    try {
        return block()
    } finally {
        val ms = (System.nanoTime() - start) / 1_000_000
        println("$name took ${if (ms < 50) "<50" else ms} ms")
    }
}

fun <T> withRetry(times: Int, block: (attempt: Int) -> T): T {
    var last: Exception? = null
    repeat(times) { attempt ->
        try {
            return block(attempt + 1)
        } catch (e: Exception) {
            println("attempt ${attempt + 1} failed: ${e.message}")
            last = e
        }
    }
    throw last!!
}

fun main() {
    val sum = timed("sum") { (1..1_000_000).sumOf { it.toLong() } }
    println(sum)

    val result = withRetry(3) { attempt ->
        if (attempt < 3) error("connection reset")
        "connected on attempt $attempt"
    }
    println(result)
}
sum took <50 ms
500000500000
attempt 1 failed: connection reset
attempt 2 failed: connection reset
connected on attempt 3

timed is inline, so the lambda can use return to exit the caller and there's no allocation for the lambda. The standard library's use { }, synchronized(lock) { }, measureTimedValue { } and withLock { } are all template methods in this style.

Decorator

A decorator wraps an object, implements the same interface and adds behavior. The tedious part in Java is forwarding every method you don't change. Kotlin's class delegation (: Interface by inner) makes the compiler generate the forwarding methods, so each decorator only contains what it changes:

interface DataSource {
    fun read(key: String): String?
    fun write(key: String, value: String)
    fun keys(): Set<String>
}

class MemorySource : DataSource {
    private val data = mutableMapOf<String, String>()
    override fun read(key: String) = data[key]
    override fun write(key: String, value: String) { data[key] = value }
    override fun keys() = data.keys.toSet()
}

// only write() is overridden; read() and keys() are forwarded by the compiler
class Logging(private val inner: DataSource) : DataSource by inner {
    override fun write(key: String, value: String) {
        println("write $key=$value")
        inner.write(key, value)
    }
}

class Uppercase(private val inner: DataSource) : DataSource by inner {
    override fun write(key: String, value: String) = inner.write(key, value.uppercase())
}

class Caching(private val inner: DataSource) : DataSource by inner {
    private val cache = mutableMapOf<String, String?>()
    override fun read(key: String) = cache.getOrPut(key) {
        println("cache miss: $key")
        inner.read(key)
    }
    override fun write(key: String, value: String) {
        cache.remove(key)
        inner.write(key, value)
    }
}

fun main() {
    val ds: DataSource = Caching(Logging(Uppercase(MemorySource())))
    ds.write("greeting", "hello")
    println(ds.read("greeting"))
    println(ds.read("greeting"))
    println(ds.keys())
}
write greeting=hello
cache miss: greeting
HELLO
HELLO
[greeting]

The decorators are stacked at the call site, and keys() works through all three layers even though no decorator mentions it. When you add a method to DataSource, the decorators keep compiling without changes. See class delegation for how by works.

When the "interface" is a single function, decorators are just functions that take and return functions. That's how HTTP middleware is usually built; see HTTP middleware and the chain of responsibility section below.

Proxy

A proxy controls access to another object: it may create it lazily (virtual proxy), check permissions (protection proxy) or cache results. lazy is a ready-made virtual proxy, and a property delegate can act as a protection proxy:

import kotlin.properties.ReadOnlyProperty

class Image(val file: String) {
    init { println("loading $file (expensive)") }
    fun draw() = println("drawing $file")
}

// virtual proxy: create the real object on first use
class Gallery(files: List<String>) {
    private val images = files.associateWith { f -> lazy { Image(f) } }
    fun show(file: String) = images.getValue(file).value.draw()
}

// protection proxy as a property delegate
fun <T> guarded(isAllowed: () -> Boolean, value: T) = ReadOnlyProperty<Any?, T> { _, prop ->
    check(isAllowed()) { "access to ${prop.name} denied" }
    value
}

var isAdmin = false

class Settings {
    val apiKey: String by guarded({ isAdmin }, "sk-123")
}

fun main() {
    val g = Gallery(listOf("a.png", "b.png"))
    println("gallery created")
    g.show("a.png")
    g.show("a.png")

    val s = Settings()
    runCatching { s.apiKey }.onFailure { println(it.message) }
    isAdmin = true
    println(s.apiKey)
}
gallery created
loading a.png (expensive)
drawing a.png
drawing a.png
access to apiKey denied
sk-123

b.png is never loaded because nobody asked for it. ReadOnlyProperty { thisRef, property -> ... } creates a delegate from a lambda; see custom delegation and lazy initialization. For a caching proxy over a whole interface, use class delegation as in the Caching decorator above.

Observer

The observer pattern lets objects subscribe to events from another object. The simplest Kotlin version keeps a list of lambdas. Returning an AutoCloseable from subscribe gives callers an easy way to unsubscribe:

class EventBus<E> {
    private val listeners = mutableListOf<(E) -> Unit>()

    fun subscribe(listener: (E) -> Unit): AutoCloseable {
        listeners += listener
        return AutoCloseable { listeners -= listener }
    }

    fun publish(event: E) = listeners.toList().forEach { it(event) }
}

sealed interface OrderEvent {
    data class Placed(val id: Int, val total: Double) : OrderEvent
    data class Shipped(val id: Int) : OrderEvent
}

fun main() {
    val bus = EventBus<OrderEvent>()
    bus.subscribe { println("audit: $it") }
    val mailer = bus.subscribe { e ->
        if (e is OrderEvent.Shipped) println("email: order ${e.id} is on its way")
    }

    bus.publish(OrderEvent.Placed(1, 99.5))
    bus.publish(OrderEvent.Shipped(1))
    mailer.close()
    bus.publish(OrderEvent.Shipped(2))
}
audit: Placed(id=1, total=99.5)
audit: Shipped(id=1)
email: order 1 is on its way
audit: Shipped(id=2)

publish iterates over a copy (toList()), so a listener can unsubscribe while an event is being delivered without causing a ConcurrentModificationException. Modeling events as a sealed interface lets listeners use when and smart casts.

For observing a single property, Delegates.observable is enough (see observable properties). In coroutine-based code, the idiomatic observable is a StateFlow (current value plus updates) or SharedFlow (a stream of events). Observers get operators like filter and map for free, and they unsubscribe by cancelling their coroutine:

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class Thermostat {
    private val _temperature = MutableStateFlow(20)
    val temperature: StateFlow<Int> = _temperature.asStateFlow()

    fun set(t: Int) { _temperature.value = t }
}

fun main() = runBlocking {
    val t = Thermostat()
    val job = launch {
        t.temperature
            .filter { it >= 25 }
            .collect { println("too hot: $it") }
    }
    val display = launch {
        t.temperature.collect { println("display: $it") }
    }
    yield()
    for (v in listOf(22, 26, 27)) {
        t.set(v)
        delay(10)
    }
    job.cancel()
    display.cancel()
}
display: 20
display: 22
too hot: 26
display: 26
too hot: 27
display: 27

The class exposes a read-only StateFlow and keeps the MutableStateFlow private, so only the owner can change the value. This example needs org.jetbrains.kotlinx:kotlinx-coroutines-core; see flows for more.

Command

A command turns a request into an object that can be stored, queued, logged or undone. When you only need to queue or delay work, a lambda already is a command object:

fun main() {
    val queue = ArrayDeque<() -> Unit>()
    var counter = 0
    queue += { counter += 10 }
    queue += { counter *= 2 }
    queue += { println("counter=$counter") }

    while (queue.isNotEmpty()) queue.removeFirst()()

    val commands: Map<String, (List<String>) -> String> = mapOf(
        "add" to { args -> args.sumOf { it.toInt() }.toString() },
        "upper" to { args -> args.joinToString(" ").uppercase() },
    )
    for (line in listOf("add 1 2 3", "upper hello there", "rm -rf")) {
        val (name, rest) = line.split(" ").let { it.first() to it.drop(1) }
        println(commands[name]?.invoke(rest) ?: "unknown command: $name")
    }
}
counter=20
6
HELLO THERE
unknown command: rm

The map from names to lambdas is a common way to implement a command dispatcher, for example for a REPL or chat bot.

Undo needs more than one function per command, so here an interface with execute and undo makes sense. A command may also need to remember state, like the text it deleted:

class Editor {
    val text = StringBuilder()
}

interface Command {
    fun execute(e: Editor)
    fun undo(e: Editor)
}

class Insert(private val s: String) : Command {
    override fun execute(e: Editor) { e.text.append(s) }
    override fun undo(e: Editor) { e.text.setLength(e.text.length - s.length) }
}

class DeleteLast(private val n: Int) : Command {
    private var removed = ""
    override fun execute(e: Editor) {
        removed = e.text.takeLast(n).toString()
        e.text.setLength(e.text.length - removed.length)
    }
    override fun undo(e: Editor) { e.text.append(removed) }
}

class History(private val editor: Editor) {
    private val done = ArrayDeque<Command>()
    private val undone = ArrayDeque<Command>()

    fun run(c: Command) { c.execute(editor); done.addLast(c); undone.clear() }
    fun undo() { done.removeLastOrNull()?.let { it.undo(editor); undone.addLast(it) } }
    fun redo() { undone.removeLastOrNull()?.let { it.execute(editor); done.addLast(it) } }
}

fun main() {
    val ed = Editor()
    val h = History(ed)
    h.run(Insert("Hello"))
    h.run(Insert(", world"))
    h.run(DeleteLast(5))
    println(ed.text)
    h.undo(); println(ed.text)
    h.undo(); println(ed.text)
    h.redo(); println(ed.text)
}
Hello, 
Hello, world
Hello
Hello, world

ArrayDeque from the standard library works as both a stack and a queue; see queues, stacks, and deques.

State

The state pattern models an object whose behavior depends on its current state. The object-oriented version has a class per state with a method per event. In Kotlin, it's usually clearer to model states and events as sealed types and write the transitions as a single function with when:

sealed interface Door {
    data object Open : Door
    data object Closed : Door
    data class Locked(val code: String) : Door
}

sealed interface Action {
    data object Close : Action
    data object OpenIt : Action
    data class Lock(val code: String) : Action
    data class Unlock(val code: String) : Action
}

fun Door.on(a: Action): Door = when (this) {
    Door.Open -> when (a) {
        Action.Close -> Door.Closed
        else -> this
    }
    Door.Closed -> when (a) {
        Action.OpenIt -> Door.Open
        is Action.Lock -> Door.Locked(a.code)
        else -> this
    }
    is Door.Locked -> when {
        a is Action.Unlock && a.code == code -> Door.Closed
        else -> this
    }
}

fun main() {
    val actions = listOf(
        Action.Close, Action.Lock("1234"), Action.OpenIt,
        Action.Unlock("0000"), Action.Unlock("1234"), Action.OpenIt,
    )
    actions.fold<Action, Door>(Door.Open) { state, action ->
        state.on(action).also { println("$state + $action -> $it") }
    }
}
Open + Close -> Closed
Closed + Lock(code=1234) -> Locked(code=1234)
Locked(code=1234) + OpenIt -> Locked(code=1234)
Locked(code=1234) + Unlock(code=0000) -> Locked(code=1234)
Locked(code=1234) + Unlock(code=1234) -> Closed
Closed + OpenIt -> Open

States are immutable values: on returns the next state instead of mutating anything, so you can fold over a list of events, log every transition and test the state machine with plain asserts. A data object gives a singleton state with a nice toString(), and a data class state can carry data (here the lock code).

Because Door is sealed, the outer when (this) has no else branch. If you add a new state, every when that doesn't handle it stops compiling.

Visitor

The visitor pattern lets you add new operations to a class hierarchy without changing the classes. In Java it requires an accept(visitor) method in every class and a visit overload per class in every visitor, which is a lot of ceremony to get double dispatch.

With a sealed hierarchy, every operation is a function with an exhaustive when. Extension functions make it read like a method:

sealed interface Expr {
    data class Num(val value: Double) : Expr
    data class Var(val name: String) : Expr
    data class Add(val left: Expr, val right: Expr) : Expr
    data class Mul(val left: Expr, val right: Expr) : Expr
}

// each "visitor" is just a function with an exhaustive when
fun Expr.eval(env: Map<String, Double>): Double = when (this) {
    is Expr.Num -> value
    is Expr.Var -> env[name] ?: error("unbound variable $name")
    is Expr.Add -> left.eval(env) + right.eval(env)
    is Expr.Mul -> left.eval(env) * right.eval(env)
}

fun Expr.show(): String = when (this) {
    is Expr.Num -> value.toString().removeSuffix(".0")
    is Expr.Var -> name
    is Expr.Add -> "(${left.show()} + ${right.show()})"
    is Expr.Mul -> "${left.show()} * ${right.show()}"
}

fun Expr.variables(): Set<String> = when (this) {
    is Expr.Num -> emptySet()
    is Expr.Var -> setOf(name)
    is Expr.Add -> left.variables() + right.variables()
    is Expr.Mul -> left.variables() + right.variables()
}

fun main() {
    val e = Expr.Mul(Expr.Add(Expr.Var("x"), Expr.Num(2.0)), Expr.Var("y"))
    println(e.show())
    println(e.variables())
    println(e.eval(mapOf("x" to 3.0, "y" to 4.0)))
}
(x + 2) * y
[x, y]
20.0

Adding a new operation means writing a new function; the Expr classes don't change. Adding a new kind of node is caught by the compiler:

sealed interface Expr {
    data class Num(val value: Double) : Expr
    data class Add(val left: Expr, val right: Expr) : Expr
    data class Neg(val e: Expr) : Expr   // newly added
}

fun Expr.eval(): Double = when (this) {
    is Expr.Num -> value
    is Expr.Add -> left.eval() + right.eval()
}
err.kt:7:27: error: 'when' expression must be exhaustive. Add the 'is Neg' branch or an 'else' branch.

This is why you should avoid else -> branches in when over sealed types: they turn this compile error into a silent bug.

Adapter

An adapter makes an existing class usable through an interface it doesn't implement. In Kotlin you often don't need a wrapper class at all: an extension function can convert the object, or add the missing API directly to a type you don't control:

import java.time.Duration
import java.util.Enumeration
import java.util.Vector

// a "legacy" API we can't change
class LegacyPrinter {
    fun printLine(chars: CharArray) = println(String(chars))
}

// the interface our code wants
fun interface Output {
    fun write(s: String)
}

// adapter as an extension function returning the target interface
fun LegacyPrinter.asOutput() = Output { printLine(it.toCharArray()) }

// adapter extensions over JDK types
val Int.seconds: Duration get() = Duration.ofSeconds(toLong())
fun <T> Enumeration<T>.asSequence(): Sequence<T> = sequence {
    while (hasMoreElements()) yield(nextElement())
}

fun greet(out: Output) = out.write("hello via adapter")

fun main() {
    greet(LegacyPrinter().asOutput())
    println(90.seconds)
    val v = Vector(listOf("a", "b", "c"))
    println(v.elements().asSequence().map { it.uppercase() }.toList())
}
hello via adapter
PT1M30S
[A, B, C]

asOutput() returns an Output created from a lambda (possible because Output is a fun interface). The standard library ships many adapters of this kind: asSequence(), asIterable(), asList() on arrays, asFlow(), Reader.buffered(), toKotlinDuration(). See extension methods.

Chain of responsibility

In a chain of responsibility, a request passes through a series of handlers, and each one either handles it or passes it to the next. With function types, building the chain is a foldRight over a list of handlers:

data class Request(val path: String, val user: String?, val body: String = "")
data class Response(val status: Int, val text: String)

fun interface Middleware {
    fun handle(req: Request, next: (Request) -> Response): Response
}

val logging = Middleware { req, next ->
    next(req).also { println("${req.path} -> ${it.status}") }
}
val auth = Middleware { req, next ->
    if (req.user == null) Response(401, "login required") else next(req)
}
val sizeLimit = Middleware { req, next ->
    if (req.body.length > 10) Response(413, "too large") else next(req)
}

fun chain(handlers: List<Middleware>, endpoint: (Request) -> Response): (Request) -> Response =
    handlers.foldRight(endpoint) { mw, next -> { req -> mw.handle(req, next) } }

fun main() {
    val app = chain(listOf(logging, auth, sizeLimit)) { req ->
        Response(200, "hello ${req.user}")
    }
    println(app(Request("/home", "ann")))
    println(app(Request("/home", null)))
    println(app(Request("/upload", "bob", "x".repeat(100))))
}
/home -> 200
Response(status=200, text=hello ann)
/home -> 401
Response(status=401, text=login required)
/upload -> 413
Response(status=413, text=too large)

foldRight starts from the endpoint and wraps it with each middleware from the last to the first, so logging runs first and sees the final response, auth can short-circuit the chain by not calling next, and sizeLimit runs only for authenticated requests. Ktor plugins and OkHttp interceptors work the same way.

Iterator

To make a custom collection iterable in Java you write an Iterator class that keeps track of the position by hand. In Kotlin, the iterator { } and sequence { } builders let you write the traversal as a normal loop and yield each element. The builder suspends after every yield until the next element is requested:

class Tree<T>(val value: T, val children: List<Tree<T>> = emptyList()) : Iterable<T> {
    // depth-first traversal written as a generator
    override fun iterator(): Iterator<T> = iterator {
        yield(value)
        for (c in children) yieldAll(c)
    }
}

fun fibonacci() = sequence {
    var a = 0L
    var b = 1L
    while (true) {
        yield(a)
        a = b.also { b += a }
    }
}

fun main() {
    val tree = Tree("root", listOf(
        Tree("a", listOf(Tree("a1"), Tree("a2"))),
        Tree("b"),
    ))
    for (n in tree) print("$n ")
    println()
    println(tree.filter { it.length == 2 })
    println(fibonacci().take(10).toList())
    println(fibonacci().first { it > 1000 })
}
root a a1 a2 b 
[a1, a2]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1597

Implementing Iterable<T> gives Tree a for loop and every collection operation (filter, map, first, ...). fibonacci() is infinite, which is fine because a sequence is lazy and computes only the elements that are actually used. See sequences and iterators.

Patterns you rarely need in Kotlin

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents