What You'll Learn
context parameters (implicit context passing, DSL design, logging/transaction/auth contexts) explained.
What are context parameters?
Introduced experimentally in Kotlin 2.1. Allows passing context to functions implicitly.
// Enable in build.gradle.kts
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xcontext-parameters")
}
}
Basics
interface Logger {
fun log(message: String)
}
// context(Logger) = callable only within Logger scope
context(logger: Logger)
fun processData(data: String) {
logger.log("Processing: $data")
// processing logic
logger.log("Done: $data")
}
// Call site
class ConsoleLogger : Logger {
override fun log(message: String) = println("[LOG] $message")
}
fun main() {
with(ConsoleLogger()) {
processData("sample") // Logger context passed implicitly
}
}
Multiple Contexts
interface TransactionScope {
suspend fun <T> execute(query: String): T
}
interface AuthContext {
val currentUserId: String
val isAdmin: Boolean
}
context(auth: AuthContext, tx: TransactionScope)
suspend fun deleteUser(userId: String) {
require(auth.isAdmin) { "Admin required" }
tx.execute<Unit>("DELETE FROM users WHERE id = '$userId'")
}
Compose DSL Combination
interface AnalyticsScope {
fun trackEvent(name: String, params: Map<String, String> = emptyMap())
}
context(analytics: AnalyticsScope)
@Composable
fun TrackedButton(
text: String,
eventName: String,
onClick: () -> Unit
) {
Button(onClick = {
analytics.trackEvent(eventName, mapOf("button" to text))
onClick()
}) {
Text(text)
}
}
Providing Context with with/run
class AppAnalytics : AnalyticsScope {
override fun trackEvent(name: String, params: Map<String, String>) {
Firebase.analytics.logEvent(name) {
params.forEach { (k, v) -> param(k, v) }
}
}
}
@Composable
fun MyScreen() {
val analytics = remember { AppAnalytics() }
with(analytics) {
TrackedButton(
text = "Purchase",
eventName = "purchase_click",
onClick = { /* purchase logic */ }
)
}
}
Summary
| Concept | Description |
|---|---|
context(T) |
Implicit context declaration |
with(instance) |
Context provision |
| Multiple contexts | context(A, B) |
| DSL design | Scoped functions |
- context parameters reduce boilerplate
- Perfect for cross-cutting concerns: Logger/Auth/Transaction
- Provide context with
with/run - Experimental feature in Kotlin 2.1+
Ready-Made Android App Templates
8 production-ready Android app templates with Jetpack Compose, MVVM, Hilt, and Material 3.
Browse templates → Gumroad
Top comments (0)