Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 233
Draculea Avatar asked Jul 13 '17 04:07

Draculea


2 Answers

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()
}
like image 191
zsmb13 Avatar answered Oct 13 '22 02:10

zsmb13


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"
like image 35
marstran Avatar answered Oct 13 '22 03:10

marstran