Overriding invoke method to build DSL

suggest change

If you have:

class MyExample(val i: Int) {
  operator fun <R> invoke(block: MyExample.() -> R) = block()
  fun Int.bigger() = this > i
}

you can write the following DSL-like code in your production code:

fun main2(args: Array<String>) {
    val ex = MyExample(233)
    ex {
        // bigger is defined in the context of `ex`
        // you can only call this method inside this context
        if (777.bigger()) kotlin.io.println("why")
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents