Kotlin从其他类调用成员扩展函数

Mik*_*ick 7 android kotlin

我想在多个类中使用此函数:

fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
}
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

这就是我想用它的方式:

class A{
fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
    }
}

class B{
constructor(){
    val a = A()
    //I want to use the function here
}}
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 15

如果将扩展函数定义为类的成员A,则该扩展函数仅在上下文中可用A.这意味着,你A当然可以直接在里面使用它.但是从另一个班级来看B,它并不是直接可见的.Kotlin有所谓的范围函数with,可用于将您的类带入范围A.下面演示了如何调用扩展函数B:

class B {
    init {
        with(A()) {
            "anything".ifNull { it, s -> }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,这主要是推荐的方法,您可以在顶层定义扩展函数,即直接在文件中:

fun <T> T?.ifNull(function: (T?, s: String) -> Unit) {
}

class A {
    init {
        "anythingA".ifNull { it, s -> }
    }
}

class B {
    init {
        "anythingB".ifNull { it, s -> }
    }
}
Run Code Online (Sandbox Code Playgroud)