First, note that an extension function defined as a member requires two receivers, one is an instance of the enclosing class (dispatch receiver, usually this
of the enclosing class) and the other is the instance of the type that the function extends (extension receiver). This is documented here.
So, to call such a function from outside the class you have to provide two receivers. Kotlin doesn't have any syntax to do that explicitly like (x, "abc").stringExtension()
, but you can provide the dispatch receiver implicitly using an extension lambda:
class C(val name: String) {
fun String.extended() = this + " extended by " + name
}
fun main(args: Array<String>) {
val c = C("c")
with(c) { println("abc".extended()) }
}
(runnable demo of this code)
In the with(...) { ... }
block, c
becomes the implicit receiver, thus allowing you to use it as a dispatch receiver in C
member extensions. This would work with any other function that uses functional types with receivers: apply
, run
, use
etc.
In your case, it would be with(o) { "hello world".extension('l') }
As @KirillRakhman noted, an extension receiver of an extension function for C
can also be implicitly used as a dispatch receiver for the extensions defined inside C
:
fun C.someExtension() = "something".extended()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…