Created
September 7, 2017 04:23
-
-
Save nosix/ec54dd2fe6822ada3b4e9100e18efa11 to your computer and use it in GitHub Desktop.
How to limit the scope of extension functions in Kotlin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Alex100 , good idea, but with a little bug
Another way:
object can't stop using the
foo
function after importingFooExtension.foo
, class will generate duplicated instance.Finally, I give up this way.