Search code examples
kotlinkotlin-extension

kotlin extension method access in another kt


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.


Solution

  • 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()
    }