另一个kt中的kotlin扩展方法访问
kotlin extension method access in another kt
我正在考虑在一个文件中为 String 添加一个 global 扩展方法,无论我在哪里使用 String,我都可以使用这个扩展。
但我没能找到这样做的方法...我现在只是将扩展程序粘贴到各处。
A.kt 中的分机:
class A{
......
fun String.add1(): String {
return this + "1"
}
......
}
并在 B.kt 中像这样访问:
class B{
fun main(){
......
var a = ""
a.add1()
......
}
}
我已经尝试了所有我可以添加的东西,比如 static
和 final
但没有任何效果。
确保您的扩展函数是 top level function, and isn't nested in a class - otherwise it will be a member extension,它只能在 class 中访问,它位于:
package pckg1
fun String.add1(): String {
return this + "1"
}
然后,如果你在不同的包中使用它,你必须像这样导入它(IDE 也应该建议):
package pckg2
import pckg1.add1
fun x() {
var a = ""
a.add1()
}
您可以使用 with
函数在定义它的 class 之外使用成员扩展。在传递给 with
的 lambda 中,this
将引用您传入的 A
的实例。这将允许您使用在 A
中定义的扩展函数。像这样:
val a = A()
val s = "Some string"
val result = with(a) {
s.add1()
}
println(result) // Prints "Some string1"
我正在考虑在一个文件中为 String 添加一个 global 扩展方法,无论我在哪里使用 String,我都可以使用这个扩展。
但我没能找到这样做的方法...我现在只是将扩展程序粘贴到各处。
A.kt 中的分机:
class A{
......
fun String.add1(): String {
return this + "1"
}
......
}
并在 B.kt 中像这样访问:
class B{
fun main(){
......
var a = ""
a.add1()
......
}
}
我已经尝试了所有我可以添加的东西,比如 static
和 final
但没有任何效果。
确保您的扩展函数是 top level function, and isn't nested in a class - otherwise it will be a member extension,它只能在 class 中访问,它位于:
package pckg1
fun String.add1(): String {
return this + "1"
}
然后,如果你在不同的包中使用它,你必须像这样导入它(IDE 也应该建议):
package pckg2
import pckg1.add1
fun x() {
var a = ""
a.add1()
}
您可以使用 with
函数在定义它的 class 之外使用成员扩展。在传递给 with
的 lambda 中,this
将引用您传入的 A
的实例。这将允许您使用在 A
中定义的扩展函数。像这样:
val a = A()
val s = "Some string"
val result = with(a) {
s.add1()
}
println(result) // Prints "Some string1"