A
A
Alexey Yukhnovets2018-12-07 17:13:42
JVM
Alexey Yukhnovets, 2018-12-07 17:13:42

Is it possible to implement contextual extension functions in Kotlin?

For example:

fun String.hello() = "world"

contextFunction {
println("".hello()) //Внутри contextFunction метод должен работать
}

println("".hello()) // А за пределами contextFunction он не должен существовать

The goal is to add methods for standard types, but only inside the dsl, so as not to pollute the global scope with these methods.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-12-07
@Feaxer

Of course it is possible. It is necessary to transfer a lambda with a receiver as a callback. And inside the receiver to determine the extension.

object Ctx {
    fun String.hello() = "world"
}

fun contextFunction(block: Ctx.() -> Unit) {
    Ctx.block()
}

fun main(args: Array<String>) {
    contextFunction {
        println("".hello())
    }
}

Still it is possible to rest and add functions to this context from the outside. Not quite in the usual way, but what if you want something strange.
val Ctx.hello2: String.() -> String get() = { "$this world" }

contextFunction{
   "hi".hello2()
}

I
illuzor, 2018-12-07
@iLLuzor

No, It is Immpossible. And I don't understand why this is necessary.
Just make a dsl method and pass your string to it (and/or anything else)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question