Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 134 ยท Idiomatic Kotlin

Context Parameters

Learn Kotlin context parameters: declare implicit dependencies with context(...), supply them with context(x) { }, use them in properties and lambdas, and know the limits.

Some values are needed almost everywhere in a program: a logger, a database transaction, a clock, a permission checker. Passing them as an ordinary parameter to every function clutters every signature and every call. Storing them in a global variable hides the dependency and makes testing painful. Kotlin's answer is context parameters: parameters that you declare on a function but that the caller does not pass by hand. The compiler finds them in the surrounding scope.

Context parameters are the successor of the older, experimental context receivers. The difference matters: a context receiver put all of its members into scope without a name, which led to confusing code. A context parameter has a name (or _ if you do not need one), so you always write logger.log(...) and it is clear where log comes from. In this lesson you will declare context parameters, supply them, use them on properties, combine several of them, and learn where they are a good fit and where they are not. You should know extension functions, lambdas and lambdas with receivers.

Declaring a context parameter

A context parameter list goes in front of the function with the keyword context. Each entry is name: Type:

Kotlin A function with a context parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

double takes one normal parameter, n, and one context parameter, logger. Inside the function body you use logger just like any other parameter. At the call site you do not write it. Instead you open a context scope with the standard function context(value) { ... }. Inside the braces, appLogger is available as an implicit argument, and every function that asks for a Logger context finds it there.

If no suitable value is in scope, the compiler refuses to build the program rather than failing at run time:

TEXT
error: no context argument for 'logger: Logger' found.
    double(21)
    ^^^^^^

Context parameters are stable in Kotlin 2.4 and need no compiler flag. They were introduced as an experimental feature in 2.2 (behind -Xcontext-parameters), so older blog posts show a flag or the old context(Logger) syntax without a name. That old form (context receivers) is deprecated; do not use it in new code.

How the compiler finds a context argument

When you call a function with context parameters, the compiler looks through everything that is implicitly available at that point: context parameters of the enclosing function, values supplied by an enclosing context(...) { } block, and implicit receivers such as the one provided by with(x) { } or a class's this. It picks the value whose type fits. Look at how the context travels down a chain of calls:

flowchart TD
    M["main()<br/>context(appLogger) { ... }"] --> P["process(order)<br/>context(logger: Logger)"]
    P --> V["validate(order)<br/>context(logger: Logger)"]
    P --> S["save(order)<br/>context(logger: Logger)"]
    V -. "same Logger passed implicitly" .-> L(("appLogger"))
    S -. "same Logger passed implicitly" .-> L
    M -. "supplies" .-> L

The caller supplies the context once; every function that declares the same context parameter receives it without extra arguments.

A function that declares a context parameter can call another function that needs the same context with no extra work, because its own context parameter is in scope:

Kotlin Passing a context down a call chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that process never mentions logger when it calls validate and save. If you later add a second dependency to save, you only change save, process and the entry point, not every function in between, as long as each one that calls it declares the context too. The compiler tells you exactly which calls are missing a context.

Anonymous contexts with underscore

Sometimes a function does not use the value itself; it only needs to pass it on to something deeper. Name the parameter _ in that case:

Kotlin Using _ when you only forward the context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

login and checkout never touch the audit object directly, so they declare it as _. They still require it, which is what forces callers to provide one. The _ name just says "I will not refer to this by name".

Several context parameters

You can list more than one, separated by commas. The caller supplies all of them; context has overloads that take several values:

Kotlin Two context parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same Audit is reused while the Clock changes between blocks. Because each type is a different class, the compiler has no doubt which value goes where. If you put two values of the same type in scope, the call becomes ambiguous and the code will not compile, so give distinct roles distinct types (a small wrapper class is cheap).

Context parameters on properties and extensions

A property with a getter (but no backing field) can also have context parameters, and so can an extension function or extension property. This is useful for operations that only make sense in a certain environment:

Kotlin Context parameters on an extension property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here asPrice reads as a natural property of an Int, yet it depends on the active Currency. Without context parameters you would need either a global currency or an explicit price(amount, currency) call everywhere.

Two limits to remember. Context parameters are not allowed on constructors or on classes, only on functions, properties with getters and function types. And a property with a context parameter cannot have a backing field or an initializer, because it has no single stored value: its result depends on the context.

Context in function types

A lambda can require a context too. Write the context types in front of the function type:

Kotlin A parameter whose lambda needs a context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The type context(Transaction) () -> Unit means "a function that takes no ordinary arguments but must be called with a Transaction in scope". Inside the lambda passed from main, the transaction is automatically available, so insert compiles even though main has no transaction of its own. This looks like a lambda with a receiver (Transaction.() -> Unit), but with an important difference: the Transaction is not this. Its members are not in scope unqualified, so nothing is silently shadowed, and a function can use a transaction without exposing all of its members to the caller.

Context parameters versus the alternatives

When should you reach for them? Compare the tools you already know:

Tool Best for Weakness
Plain parameter Almost everything Repeated in every signature of a long call chain
Receiver (fun Foo.bar()) Operations that belong to Foo, DSLs One receiver; all members spill into scope
Lambda with receiver (Foo.() -> Unit) Builders and DSLs, see type-safe builders Members leak into nested blocks
Global or singleton Quick scripts Hidden, hard to test
Context parameter Cross-cutting dependencies passed through many layers Hides the argument at call sites, so use sparingly
Dependency injection framework Large applications Heavy, runtime wiring

Good candidates are things that are truly ambient: a logger, a transaction, a security principal, an error-collecting scope, a coroutine-like scope object. Poor candidates are values that change the meaning of a single call (a name, a count, a price). Those belong in an ordinary parameter, where a reader sees them.

A useful test: if reading process("book") and not seeing the logger would surprise nobody, it is a good context. If it would surprise someone, make it explicit.

Things to know before you adopt them

  • Everything is resolved at compile time. There is no reflection and no runtime lookup. A context parameter compiles to an extra argument in the generated method, which is why double above shows up with one more parameter when called from Java.
  • Java cannot use the context(...) { } syntax. From Java you pass the context values as the first arguments. Keep public library APIs for Java callers explicit if they matter.
  • Overuse harms readability. Three or four contexts on one function are a sign you may want one object that bundles them, for example a Environment class with a logger, clock and database, and a single context of that type.
  • Members are not in scope. Unlike context receivers, you cannot write log("x") unqualified. That is deliberate and is why the feature replaced them.

Do not use context parameters to hide important behavior such as authorization decisions or data deletion. If a caller cannot tell from the call site that something powerful happens, code review gets much harder. Make such choices explicit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a caller supply a context parameter to a function?

    The caller does not pass context arguments by hand. The compiler resolves them from the surrounding scope, typically one created with context(value) { ... }, or from the enclosing function's own context parameters.
  2. 2. What does the name _ mean in context(_: Audit)?

    An underscore declares an anonymous context parameter. The caller must still provide it, and any function this one calls can receive it, but the body cannot use it by name.
  3. 3. Where are context parameters NOT allowed?

    They are allowed on functions, properties without a backing field, and function types. Constructors and class declarations cannot have them.
  4. 4. Why did context parameters replace context receivers?

    With a named parameter you write logger.log(...), so it is obvious where a call comes from. Receivers made all members implicitly visible and could shadow each other.

Summary

  • A context parameter is declared with context(name: Type) before a function or property and is filled in by the compiler from the surrounding scope.
  • Supply values with context(a, b) { ... }; a function that declares the same context passes it on automatically.
  • Use _ as the name when a function only forwards the context.
  • Properties with getters, extensions and function types such as context(Transaction) () -> Unit can have context parameters; constructors and classes cannot.
  • Missing contexts are compile errors, and resolution happens entirely at compile time.
  • Use them for ambient dependencies like loggers and transactions; keep meaningful inputs as ordinary parameters.

Next: Result Type