Kotlin call member Extension function from other c

2020-04-04 17:10发布

问题:

I would like to use this function in multiple classes:

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

How can I accomplish this?

This is how I would like to use it:

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

class B{
constructor(){
    val a = A()
    //I want to use the function here
}}

回答1:

If you define an extension function as a member of a class A, that extension function is only usable in the context of A. That means, you can use it inside A directly, of course. From another class B though, it's not directly visible. Kotlin has so called scope functions like with, which may be used for bringing your class into the scope of A. The following demonstrates how the extension function is called inside B:

class B {
    init {
        with(A()) {
            "anything".ifNull { it, s -> }
        }
    }
}

As an alternative, and this is mostly the recommended approach, you would define extension functions top-level, i.e. in a file directly:

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

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

class B {
    init {
        "anythingB".ifNull { it, s -> }
    }
}