First, note that the extension function, defined as a member, requires two receivers, one is an instance of the wrapper class (the dispatcher-receiver, usually this enclosing class), and the other is an instance of the type the function extends (extension receiver). This is described here .
So, to call such a function from outside the class, you must provide two receivers. Kotlin has no syntax to do this explicitly as (x, "abc").stringExtension() , but you can provide a dispatch manager implicitly using the lambda extension :
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 with(...) { ... } c becomes an implicit receiver, which allows you to use it as a receiver for sending member extensions to c . This will work with any other function that uses function types with receivers: apply , run , use , etc.
In your case, it will 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 send receiver for extensions defined inside c
fun C.someExtension() = "something".extended()
source share