Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to limit the scope of extension functions in Kotlin.
interface Extension
// Why is keyword `class` instead of `object`?
// Because we can use the `foo` function after importing `FooExtension.foo`.
class FooExtension : Extension {
fun String.foo(): String = "Foo${this}"
}
class BarExtension : Extension {
fun String.bar(): String = "Bar${this}"
}
fun <E : Extension> extendWith(extension: E, block: E.() -> Unit) = block.invoke(extension)
fun main(args: Array<String>) {
val name = "Buz Bar"
// println(name.foo())
// println(name.bar())
extendWith(FooExtension()) {
println(name.foo())
// println(name.bar())
extendWith(BarExtension()) {
println(name.foo())
println(name.bar())
}
}
}
@Alex100

This comment has been minimized.

Copy link

commented Oct 17, 2018

How about this solution:

interface Extension
operator fun <E: Extension> E.invoke(body: E.() -> Unit) = Unit

object FooExtension : Extension {
    fun String.foo(): String = "Foo${this}"
}

object BarExtension : Extension {
    fun String.bar(): String = "Bar${this}"
}

fun main(args: Array<String>) {
    val name = "Buz Bar"

//    println(name.foo())
//    println(name.bar())

    FooExtension {
        println(name.foo())
//        println(name.bar())

        BarExtension {
            println(name.foo())
            println(name.bar())
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.