kotlin extension method access in another kt
Make sure your extension function is a top level function, and isn't nested in a class - otherwise it will be a member extension, which is only accessible inside the class that it's in:
package pckg1
fun String.add1(): String {
return this + "1"
}
Then, if your usage of it is in a different package, you have to import it like so (this should be suggested by the IDE as well):
package pckg2
import pckg1.add1
fun x() {
var a = ""
a.add1()
}
You can use the with
-function to use a member extension outside the class where it was defined. Inside the lambda passed to with
, this
will refer to the instance of A
you pass in. This will allow you to use extension functions defined inside A
. Like this:
val a = A()
val s = "Some string"
val result = with(a) {
s.add1()
}
println(result) // Prints "Some string1"