16

I'm thinking about adding a global extension method to String in just one file,and wherever i use a String i can always use this extension.

But i failed to find a way to do so...i just paste the extension everywhere now.

extension here in A.kt:

class A{
    ......
    fun String.add1(): String {
        return this + "1"
    }
    ......
}

and access like this in B.kt:

class B{
    fun main(){
        ......
        var a = ""
        a.add1()
        ......
    }
}

I've tried everyting i can add like static and final but nothing worked.

Draculea
  • 303
  • 2
  • 7

2 Answers2

31

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()
}
zsmb13
  • 85,752
  • 11
  • 221
  • 226
13

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"
marstran
  • 26,413
  • 5
  • 61
  • 67