angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
419 stars 58 forks source link

Context receivers #84

Open Miha-x64 opened 1 year ago

Miha-x64 commented 1 year ago

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.

TWiStErRob commented 1 year ago

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