Let's assume I have a public extension function in...
# announcements
s
Let's assume I have a public extension function in a class or interface
Copy code
class A {
    fun String.hello() = "hello $this"
}
Is there any simpler solution of calling this function instead of having to use
with()
?
Copy code
val a = A()
"Some string".run {
    with(a) { hello() }
}
s
Place the function outside a class or put in a companion object, then, in both cases, import it to have just a function available. Then you will be able to call just
Copy code
"Some String".hello()
s
I'm aware of global extension functions 😉 I'm explicitely asking for extension functions on classes. This is just a simplified example. The real reason I'm using this is for a function inside a class of the type
Copy code
fun CoroutineScope.doSomething()
instead of
fun doSomething(CoroutineScope)
s
I was implementing the functions in companion objects, like this:
Copy code
class X {
    companion object {
        fun String.hello() = "hello $this"
    }
}
Copy code
import X.Companion.hello

fun a() {
    "Some String".hello()
}
Maybe not the best solution, but at the end I had a simple function call on a string
s
But now what if the extension functions needs to access properties of class
X
? This would no longer work inside a companion object
s
Some properties also can be in the companion object, so they are like static fields in java. But if you need to have some properties of an object of the class X, then you can have this:
Copy code
class X {

    val aField: Int = 10

    companion object {
        fun String.hello(x: X) = "hello $this ${x.aField}"
    }
}
Copy code
import X.Companion.hello

fun a() {
    val x = X()
    "Some String".hello(x)
}
m
As Kotlin is an open source language there are proposals to change that. E. g. https://github.com/Kotlin/KEEP/pull/87. But be aware that this isn't released and is still in the proposal state.
👍 1