Access kotlin extension in another kt

I am thinking of adding a global extension method to String in only one file, and wherever I use String, I can always use this extension.

But I could not find a way to do this ... I just paste the extension everywhere.

extension here in A.kt:

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

and access this in B.kt:

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

I tried everything I can add as staticand final, but nothing worked.

+4
source share
2 answers

, - , , :

package pckg1

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

, , ( IDE):

package pckg2

import pckg1.add1

fun x() {
    var a = ""
    a.add1()
}
+5

with - , . , with, this A, . , A. :

val a =  A()
val s = "Some string"
val result = with(a) {
    s.add1()
}
println(result) // Prints "Some string1"
+3

Source: https://habr.com/ru/post/1681322/


All Articles