簡體   English   中英

Kotlin 中是否有可能有一個帶有可為空接收器的成員函數?

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

我可以使用可為空的接收器而不是成員函數來實現擴展函數。 這有效:

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")
}

但這不會:

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")
}

我的解決方案:我的目標是讓方法檢測問題並處理它,而不是讓調用者這樣做。 我最終做的是將函數放在伴隨對象中,這為我提供了我想要的封裝並允許我處理問題。

您可以編寫這樣的擴展函數,嵌套在類中,但嵌套將擴展函數的范圍限制在類內,類似於將其設置為protected 這可能有用,在類的其他實例上調用它:

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

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

如果你想在可為空的實例上調用它,你應該簡單地在類之外定義它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM