contextOf

context(context: A)
inline fun <A> contextOf(): A(source)

Retrieves the context argument, extension or dispatch receiver in scope with the given type. The compiler ensures that at least one such given value exists. If more than one is found, more nested scopes are prioritized, and otherwise an ambiguity error is raised by the compiler.

You must always provide a type argument to contextOf, even if the type could be inferred from the context.

Since Kotlin

2.2

Samples


fun main() { 
   //sampleStart 
   abstract class Logger { abstract fun log(message: String) }
class ConsoleLogger : Logger() { override fun log(message: String) = println(message) }

fun <A> withConsoleLogger(block: context(Logger) () -> A): A =
    context(ConsoleLogger()) { block() }

withConsoleLogger {
    contextOf<Logger>().log("start")
    println("work")
    contextOf<Logger>().log("end")
} 
   //sampleEnd
}

fun main() { 
   //sampleStart 
   abstract class Logger { abstract fun log(message: String) }
class ConsoleLogger : Logger() { override fun log(message: String) = println(message) }

fun <A> withConsoleLogger(block: Logger.() -> A): A =
    with(ConsoleLogger()) { block() }

withConsoleLogger {
    contextOf<Logger>().log("start")
    println("work")
    contextOf<Logger>().log("end")
} 
   //sampleEnd
}