Answer the question
In order to leave comments, you need to log in
Is it possible to implement contextual extension functions in Kotlin?
For example:
fun String.hello() = "world"
contextFunction {
println("".hello()) //Внутри contextFunction метод должен работать
}
println("".hello()) // А за пределами contextFunction он не должен существовать
Answer the question
In order to leave comments, you need to log in
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())
}
}
val Ctx.hello2: String.() -> String get() = { "$this world" }
contextFunction{
"hi".hello2()
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question