androidengineers.Book a session

Advanced Language Features

Context Parameters (replacing context receivers) — status & examples

article15 minHard

Make implicit dependencies visible in the declaration

Context parameters declare dependencies supplied by the surrounding context. They replace the older experimental context-receiver syntax. This is a version-sensitive feature: use the documentation matching your compiler and enable feature flags only when that version requires them.

interface StudyLog { fun write(message: String) }

context(log: StudyLog)
fun recordStudy(topic: String) {
    log.write("Studied $topic")
}

The function requires a StudyLog even though it is not an ordinary positional parameter. Current documentation shows a context(logInstance) { recordStudy("Kotlin") } call scope. Explicit context arguments are a separate experimental capability with their own opt-in flag; do not assume every context-related syntax has the same stability status.

A constructor-injected dependency or ordinary function parameter remains a clear alternative, especially in libraries supporting older compilers. Two equally applicable values can create ambiguous resolution.

Exercise

Implement a recording log and invoke this function with your compiler's supported context syntax. Rewrite it with an explicit parameter and compare call-site clarity.

Check: document the compiler version used and demonstrate the compiler error when the required context is absent.

Reference: Context parameters

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Context Parameters (replacing context receivers) — status & examples | Kotlin Core Programming | Android Engineers