Skip to content

Instantly share code, notes, and snippets.

@wafna
Last active May 5, 2023 02:31
Show Gist options
  • Save wafna/49c7ecde88ac60ae8c46d811326b3b9c to your computer and use it in GitHub Desktop.
Save wafna/49c7ecde88ac60ae8c46d811326b3b9c to your computer and use it in GitHub Desktop.
interface MyContext {
fun boom()
}
// You can specify and bind the context explicitly...
context(MyContext)
fun contextualizedHigherOrderFunction1(f: MyContext.() -> Unit) {
// see https://github.com/Kotlin/KEEP/blob/master/proposals/context-receivers.md#referencing-specific-receiver
[email protected]()
}
// ... or not!
fun contextualizedHigherOrderFunction2(f: () -> Unit) {
f()
}
context(MyContext)
fun thingy() {
boom()
}
fun main() {
val myContext = object : MyContext {
override fun boom() {
println("boom")
}
}
with(myContext) {
contextualizedHigherOrderFunction1 { thingy() }
contextualizedHigherOrderFunction2 { thingy() }
println("out go the lights")
}
}
@wafna
Copy link
Author

wafna commented May 5, 2023

You can specify the context receiver of a higher order function, or not!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment