Context parameters

suggest change

Some values are needed by many functions down a call chain: a logger, a database transaction, the current user session, a Comparator. Passing them as a regular parameter to every function is noisy, and storing them in a global makes code hard to test.

Context parameters are a third option. A function declares them in a context(...) clause before fun, and the compiler passes them automatically from the caller's scope:

context(logger: Logger)
fun startServer() { ... }

startServer can only be called where a Logger is available, and the compiler checks that.

Context parameters were added as a preview in Kotlin 2.2 (enabled with the -Xcontext-parameters compiler flag). On Kotlin 2.4 they compile without any flag or opt-in, and passing -Xcontext-parameters only produces a "redundant" warning. They replace the older experimental context receivers (-Xcontext-receivers), which are now an error. See Migrating from context receivers below.

All examples were compiled and run with Kotlin 2.4.21 on JDK 25.

For context parameters used as lightweight dependency injection, see also Dependency injection.

Declaring and calling

A context parameter has a name and a type, just like a regular parameter. Inside the function it's used by name:

interface Logger { fun log(msg: String) }

class ConsoleLogger(private val prefix: String) : Logger {
    override fun log(msg: String) = println("$prefix $msg")
}

context(logger: Logger)
fun loadConfig(path: String): Map<String, String> {
    logger.log("loading $path")
    return mapOf("port" to "8080")
}

context(logger: Logger)
fun startServer() {
    val config = loadConfig("app.conf")   // Logger passed implicitly
    logger.log("listening on ${config["port"]}")
}

fun main() {
    with(ConsoleLogger("[main]")) {
        startServer()
    }
    context(ConsoleLogger("[ctx]")) {
        startServer()
    }
}
[main] loading app.conf
[main] listening on 8080
[ctx] loading app.conf
[ctx] listening on 8080

There are three ways to provide a context argument:

A function can declare several context parameters: context(logger: Logger, tx: Transaction). They come before any extension receiver and the regular parameters.

When no matching value is in scope, the call doesn't compile:

interface Logger { fun log(msg: String) }

context(logger: Logger)
fun startServer() = logger.log("start")

fun main() {
    startServer()
}
e1.kt:7:5: error: no context argument for 'logger: Logger' found.
    startServer()
    ^^^^^^^^^^^

Only context parameters and implicit receivers (this of a with block, of an extension function, of a class member, of a lambda with receiver) are candidates. A local variable val logger = ConsoleLogger() is not picked up automatically. Context arguments also can't be passed by name at the call site; use context(...) or with(...) instead.

How the context is resolved

The compiler looks for a value whose type is the context parameter's type or a subtype of it, searching from the innermost scope outwards:

interface Logger { fun log(msg: String) }
class ConsoleLogger(private val name: String) : Logger {
    override fun log(msg: String) = println("[$name] $msg")
    override fun toString() = "ConsoleLogger($name)"
}

context(logger: Logger)
fun info(msg: String) = logger.log("INFO $msg")

// anonymous: not used directly, only passed on
context(_: Logger)
fun migrate() {
    info("migrating")
    info("done")
}

// contextOf<T>() fetches an anonymous context value
context(_: Logger)
fun whoLogs() = println("logger is ${contextOf<Logger>()}")

fun Logger.extension() = info("from an extension receiver")

fun main() {
    val outer = ConsoleLogger("outer")
    context(outer) {
        migrate()
        context(ConsoleLogger("inner")) {
            info("closest scope wins")
        }
        info("back to outer")
        whoLogs()
    }
    outer.extension()
}
[outer] INFO migrating
[outer] INFO done
[inner] INFO closest scope wins
[outer] INFO back to outer
logger is ConsoleLogger(outer)
[outer] INFO from an extension receiver

This example also shows anonymous context parameters. When a function only passes the context on to other functions, name it _. If you do need the value, contextOf<Logger>() returns it.

Two candidates of a matching type at the same level are an error, not a guess:

interface Logger { fun log(msg: String) }
class L(val n: String) : Logger { override fun log(msg: String) = println("$n $msg") }

context(logger: Logger)
fun hello() = logger.log("hello")

fun main() {
    context(L("a"), L("b")) {
        hello()
    }
}
e4.kt:9:9: error: multiple potential context arguments for 'logger: Logger' in scope.
        hello()
        ^^^^^

Because resolution is by type, use specific types for contexts (Logger, Transaction, Session). A context parameter of type String or Int would match any with("...") block.

Context properties

Properties can have a context too. They can't store anything, because the value depends on the context, so they need a getter:

data class User(val name: String, val roles: Set<String>)
class Session(val user: User?, val locale: String)

context(session: Session)
val currentUser: User
    get() = session.user ?: error("not logged in")

context(session: Session)
val isAdmin: Boolean
    get() = session.user?.roles?.contains("admin") == true

context(session: Session)
fun greeting(): String {
    val hello = if (session.locale == "de") "Hallo" else "Hello"
    return "$hello, ${currentUser.name}" + if (isAdmin) " (admin)" else ""
}

fun main() {
    context(Session(User("Ann", setOf("admin")), "en")) {
        println(greeting())
    }
    context(Session(User("Jonas", emptySet()), "de")) {
        println(greeting())
    }
}
Hello, Ann (admin)
Hallo, Jonas

An initializer is rejected:

class Session(val locale: String)
context(session: Session)
val locale: String = "en"
e5.kt:2:1: error: property with context parameters cannot be initialized because it has no backing field.

Contextual function types

A function type can have a context as well: context(Logger) (String) -> Unit. A lambda of that type has the context in scope in its body. To call it, either pass the context as the first argument, or call it where the context is available:

interface Logger { fun log(msg: String) }
class ConsoleLogger(private val name: String) : Logger {
    override fun log(msg: String) = println("[$name] $msg")
}

context(logger: Logger)
fun info(msg: String) = logger.log("INFO $msg")

fun main() {
    // a lambda with a context: the context is in scope inside the body
    val greet: context(Logger) (String) -> Unit = { name -> info("hello $name") }

    val logger = ConsoleLogger("app")
    greet(logger, "Ann")          // context first, then the regular arguments

    with(logger) {
        greet("Bob")              // context taken from the scope
    }

    // the same value works where an ordinary function type is expected
    val plain: (Logger, String) -> Unit = greet
    plain(ConsoleLogger("plain"), "Cid")
}
[app] INFO hello Ann
[app] INFO hello Bob
[plain] INFO hello Cid

At runtime context(Logger) (String) -> Unit is the same as (Logger, String) -> Unit, which is why the assignment to plain compiles. See Function type for function types in general.

Callable references to functions with context parameters aren't supported yet. ::info fails with "callable reference to 'context(logger: Logger) fun info(msg: String): Unit' is unsupported because it has context parameters." Wrap the call in a lambda instead.

Scoped capabilities: transactions

Contextual function types make it possible to write a function like transaction { ... } that provides a capability only inside its block. Functions that need the capability declare it as a context, so they can't be called anywhere else:

class Transaction(val id: Int) {
    private val pending = mutableListOf<String>()
    fun execute(sql: String) { pending += sql }
    fun commit() = println("tx$id commit ${pending.size} statements: $pending")
    fun rollback() = println("tx$id rollback ${pending.size} statements")
}

var nextId = 1

// the block receives a Transaction as a context
fun <R> transaction(block: context(Transaction) () -> R): R {
    val tx = Transaction(nextId++)
    try {
        val result = block(tx)          // pass the context explicitly
        tx.commit()
        return result
    } catch (e: Exception) {
        tx.rollback()
        throw e
    }
}

// can only be called inside a transaction
context(tx: Transaction)
fun insertUser(name: String): Int {
    tx.execute("insert into users(name) values ('$name')")
    return name.length
}

context(tx: Transaction)
fun deleteUser(name: String) {
    if (name == "root") throw IllegalArgumentException("can't delete root")
    tx.execute("delete from users where name = '$name'")
}

fun main() {
    val n = transaction {
        insertUser("ann")
        insertUser("bob")
    }
    println("result: $n")

    try {
        transaction {
            deleteUser("bob")
            deleteUser("root")
        }
    } catch (e: IllegalArgumentException) {
        println("error: ${e.message}")
    }
}
tx1 commit 2 statements: [insert into users(name) values ('ann'), insert into users(name) values ('bob')]
result: 3
tx2 rollback 1 statements
error: can't delete root

Calling insertUser("ann") outside a transaction { } block is a compile error (no context argument for 'tx: Transaction' found). The same pattern works for "must hold a lock", "must run inside a request", or "needs permission X": the requirement becomes part of the function's signature.

Compared to block: Transaction.() -> R (a lambda with receiver), the context version doesn't change this inside the block, so commit() and the other members of Transaction aren't accidentally callable there. Only functions that declare the context can use it.

Building DSLs

Type-safe builders traditionally put every DSL function in the builder class as a member. With context parameters they can be top-level functions, so anyone can add new ones, and they can be combined with an extension receiver:

class Markdown {
    private val out = StringBuilder()
    fun line(s: String = "") { out.appendLine(s) }
    override fun toString() = out.toString()
}

fun markdown(block: context(Markdown) () -> Unit): String {
    val md = Markdown()
    block(md)
    return md.toString()
}

context(md: Markdown)
fun h1(text: String) { md.line("# $text"); md.line() }

context(md: Markdown)
fun bullets(vararg items: String) {
    for (item in items) md.line("- $item")
    md.line()
}

context(md: Markdown)
operator fun String.unaryPlus() { md.line(this); md.line() }

// a helper written by a user of the DSL, outside the Markdown class
context(md: Markdown)
fun <T> table(rows: List<T>, vararg columns: Pair<String, (T) -> Any>) {
    md.line(columns.joinToString(" | ", "| ", " |") { it.first })
    md.line(columns.joinToString(" | ", "| ", " |") { "---" })
    for (row in rows) {
        md.line(columns.joinToString(" | ", "| ", " |") { it.second(row).toString() })
    }
}

data class Lang(val name: String, val year: Int)

fun main() {
    val langs = listOf(Lang("Kotlin", 2011), Lang("Go", 2009))
    val text = markdown {
        h1("Languages")
        +"Two languages from the 2000s and 2010s."
        bullets("statically typed", "garbage collected")
        table(langs, "Name" to { it.name }, "Year" to { it.year })
    }
    print(text)
}
# Languages

Two languages from the 2000s and 2010s.

- statically typed
- garbage collected

| Name | Year |
| --- | --- |
| Kotlin | 2011 |
| Go | 2009 |

String.unaryPlus has both an extension receiver (the string) and a context (the document). Inside markdown { } the low-level line() member isn't visible (unresolved reference 'line'), so the DSL exposes only the functions written for it. More DSL techniques are in DSL Building.

Operators that depend on the context

A context can also change how an operator behaves. This compareTo works for any type, using whatever Comparator is in scope:

data class Version(val major: Int, val minor: Int)

// comparison operators driven by whatever Comparator is in context
context(comparator: Comparator<T>)
operator fun <T> T.compareTo(other: T): Int = comparator.compare(this, other)

context(_: Comparator<T>)
fun <T> largest(a: T, b: T): T = if (a >= b) a else b

val byVersion = compareBy<Version>({ it.major }, { it.minor })

fun main() {
    val a = Version(1, 10)
    val b = Version(2, 0)
    with(byVersion) {
        println(a < b)
        println(largest(a, b))
    }
    with(compareBy<String> { it.length }) {
        println(largest("fig", "apple"))  // by length
        println("fig" < "apple")          // member String.compareTo wins
    }
}
true
Version(major=2, minor=0)
apple
false

Note the last line. String has its own compareTo member, and a member always beats an extension, so "fig" < "apple" still compares alphabetically. Inside the generic largest, T has no compareTo member, so the contextual one is used and the strings are compared by length.

Member functions and interfaces

Member functions can declare context parameters too, and overrides must repeat the same context:

interface Logger { fun log(msg: String) }
class Clock(val now: Long)

interface Job {
    context(logger: Logger, clock: Clock)
    fun run()
}

class Cleanup(private val days: Int) : Job {
    context(logger: Logger, clock: Clock)
    override fun run() {
        val cutoff = clock.now - days * 86_400L
        logger.log("deleting files older than $cutoff")
    }
}

class Report : Job {
    context(logger: Logger, clock: Clock)
    override fun run() = logger.log("report at ${clock.now}")
}

fun main() {
    val jobs = listOf(Cleanup(days = 7), Report())
    val logger = object : Logger {
        override fun log(msg: String) = println("job: $msg")
    }
    context(logger, Clock(now = 1_800_000_000)) {
        jobs.forEach { it.run() }
    }
}
job: deleting files older than 1799395200
job: report at 1800000000

Classes themselves can't have a context:

interface Logger { fun log(msg: String) }

context(logger: Logger)
class Service {
    fun run() = logger.log("run")
}
e3.kt:3:1: error: context parameters on classes are unsupported.

Use a constructor parameter for a dependency the whole object needs.

Calling from Java

On the JVM context parameters become ordinary leading parameters. For

context(logger: Logger)
fun info(msg: String) = logger.log(msg)

context(logger: Logger)
val level: String get() = "INFO"

javap shows:

public static final void info(Logger, java.lang.String);
public static final java.lang.String getLevel(Logger);

Java callers pass the context values explicitly, first.

Migrating from context receivers

Kotlin 1.6.20 introduced experimental context receivers with the syntax context(Logger): a type without a name, whose members were callable directly in the body. That design was dropped. On Kotlin 2.4 the old code fails:

context(Logger)
fun startServer() {
    log("start")
}
e2.kt:3:9: error: context parameters must be named. Use '_' to declare an anonymous context parameter.
context(Logger)
        ^^^^^^
e2.kt:5:5: error: unresolved reference 'log'.
    log("start")
    ^^^

and the old flag is rejected:

error: experimental context receivers are superseded by context parameters.
Remove the '-Xcontext-receivers' compiler argument and migrate to the new syntax.

The main difference is that a context parameter is not an implicit receiver: you can't call log() without a qualifier. There are three ways to migrate a function:

interface Logger { fun log(msg: String) }
class ConsoleLogger : Logger { override fun log(msg: String) = println("log: $msg") }

// 1. name the parameter and call through it
context(logger: Logger)
fun startServer() {
    logger.log("starting")
}

// 2. keep the receiver-style body by opening a scope
context(logger: Logger)
fun stopServer() = with(logger) {
    log("stopping")
}

// 3. anonymous parameter, fetched with contextOf when needed
context(_: Logger)
fun restartServer() {
    stopServer()
    contextOf<Logger>().log("restarting")
    startServer()
}

fun main() {
    with(ConsoleLogger()) {
        restartServer()
    }
}
log: stopping
log: restarting
log: starting

Other migration steps:

When to use context parameters

Good fits:

Not a good fit:

Limitations in Kotlin 2.4:

Feedback about page:

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



Table Of Contents