简体   繁体   中英

Is it possible in Kotlin to have a member function with a nullable receiver?

I can implement an extension function with a nullable receiver but not a member function. This works:

class TestMe (var xyz:String) {
}
fun TestMe?.textX(xxx:String) {
    if (this != null)
        xyz = xxx
    else println("this is null")
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
    val x : TestMe? = null
    x.textX("whatever")
    println("hello world")
}

But this doesn't:

class TestMe (var xyz:String) {
    fun TestMe?.textX(xxx:String) {
        if (this != null)
            xyz = xxx
        else println("this is null")
    }
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
    val x : TestMe? = null
    x.textX("whatever")
    println("hello world")
}

The solution for me : My goal here was to have the method detect the problem and deal with it rather than have the caller do that. What I ended up doing was to put the function in the companion object which gives me the encapsulation I wanted and also allows me to deal with problems.

You can write extension functions like this, nested inside a class, but nesting limits the extension function's scope to within the class, similar to making it protected . This potentially could have a use, calling it on other instances of the class:

class Test {
    fun Test?.foo() = println("foo ext $this")

    fun bar(other: Test?) {
        other.foo()
    }
}

If you want to call it on nullable instances, you should simply define it outside the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM