Last active
May 5, 2023 02:31
-
-
Save wafna/49c7ecde88ac60ae8c46d811326b3b9c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can specify the context receiver of a higher order function, or not!