Sobes.tech
Senior

What are 'context receivers' and how do they function in Kotlin?

sobes.tech AI

Answer from AI

Context receivers are an experimental feature of Kotlin that allows functions, properties, or classes to require the presence of instances of certain types in the call scope. This mechanism enables implicit dependency passing.

How they work:

  1. Declaration: They are added to a member declaration using the syntax context(...) before ....

    // Declaration of a function requiring context types Logger and Analytics
    context(Logger, Analytics)
    fun processData(data: String) {
        // Can use Logger and Analytics without explicit passing
        log("Processing data: $data")
        trackEvent("DataProcessed", mapOf("size" to data.length))
    }
    
    class Logger { fun log(message: String) { println(message) } }
    class Analytics { fun trackEvent(name: String, params: Map<String, Any>) { println("$name: $params") } }
    
  2. Call: To invoke a function with context receivers, instances of the required types must be available in the call scope. This can be achieved by:

    • Explicitly creating instances.
    • Having instances as context receivers of an outer function or class.
    • Using with or other scope functions to provide the context.
    fun main() {
        // Create necessary context instances
        val myLogger = Logger()
        val myAnalytics = Analytics()
    
        // Provide contexts using with
        with(myLogger) {
            with(myAnalytics) {
                // In this scope, myLogger and myAnalytics are available as contexts
                processData("some important data")
            }
        }
    }
    
  3. Inside access: Inside a member declared with context receivers, instances of these types are directly accessible as if they were regular receivers or variables in scope.

Advantages:

  • Reduced boilerplate: Eliminates the need to explicitly pass common dependencies via function parameters.
  • Improved readability: Allows focusing on business logic rather than infrastructure dependency passing.
  • Encapsulation: Clearly indicates which contexts are necessary for the member to perform its task.

It is important to note that context receivers are still an experimental feature and may change in future Kotlin versions.

What are 'context receivers' and how do they function… - sobes.tech