kotlin-puzzlers icon indicating copy to clipboard operation
kotlin-puzzlers copied to clipboard

Context receivers

Open Miha-x64 opened this issue 2 years ago • 1 comments

The feature is initially designed in ambiguous way. Companions are for illustration because identifier is a type and value at the same time.

object Wtf
fun context(i: Wtf) {
    Throwable().printStackTrace()
}

context(Wtf)
fun foo() {

    context(Wtf)
    fun bar() {
    }
}

fun main() {
    Wtf.run { foo() }
}

Answer: context() on a top-level fun is a context accepting a type. context() above a local function is just an invocation accepting a value. The only stack trace will be printed, with foo() on top of stack.

Miha-x64 avatar Apr 06 '23 10:04 Miha-x64

Good old soft keywords, nice one! Highlighting in IDE helps though.

TWiStErRob avatar Apr 06 '23 10:04 TWiStErRob