F. P. Freely
F. P. Freely

Reputation: 1134

Kotlin Context with higher order functions?

How does one define higher order functions with contexts?

Here's a simple example.

interface MyContext {
    fun herp()
}

// How does one invoke f with the context as receiver?
context(MyContext)
fun contextualizedHigherOrderFunction(f: MyContext.() -> Unit) {
    f() // nope
    this.f() // nope
}

How do I get the context into the receiver of f?

Upvotes: 2

Views: 86

Answers (2)

F. P. Freely
F. P. Freely

Reputation: 1134

UPDATE:

@Sweeper's answer works great. Also, you can just ignore the context in the type of f. Both are presented, below:

interface MyContext {
    fun boom()
}

// You can specify and bind the context explicitly.
context(MyContext)
fun contextualizedHigherOrderFunction1(f: MyContext.() -> Unit) {
    [email protected]()
}

// Or not!
context(MyContext)
fun contextualizedHigherOrderFunction2(f: () -> Unit) {
    f()
}

context(MyContext)
fun thingy() {
    boom()
}

fun main() {
    val myContext = object : MyContext {
        override fun boom() {
            println("boom")
        }
    }
    with(myContext) {
        boom()
        contextualizedHigherOrderFunction1 { thingy() }
        contextualizedHigherOrderFunction2 { thingy() }
        println("out go the lights")
    }
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 271735

You can access the context receiver by using a qualified this expression. You can use the type name as the label in this case

[email protected]()

Alternatively, pass it as a parameter:

f(this@MyContext)

For more complicated receiver type names, see how they translate to a label here.

Upvotes: 3

Related Questions