Kotlin 操作符:run、with、let、also、apply 的差異與選擇

Kotlin 的一些操作符非常相似,我們有時(shí)會(huì)不確定使用哪種功能。在這里我將介紹一個(gè)簡(jiǎn)單的方法來(lái)清楚地區(qū)分他們的差異,最后以及如何選擇使用。

首先我們以下這個(gè)代碼:

class MyClass {
    fun test() {
        val str: String = "Boss"
        val result = str.let {
             print(this) // 接收者
             print(it) // 參數(shù)
             69 //區(qū)間返回值
        }
        print(result)
    }
}

在上面?zhèn)€例子中,我們使用了 let 操作符,當(dāng)使用這個(gè)函數(shù)時(shí),我們所需要問(wèn)題的有三點(diǎn):

  • this 的含義(接收器)
  • it 的含義(參數(shù))
  • result 最終得到的什么

因?yàn)槲覀兪褂玫氖?let,所以對(duì)應(yīng)是:

  • 『 this 』為『 this @ MyClass 』, this 是 MyClass 的實(shí)例,因?yàn)?test() 是 MyClass 的一個(gè)方法。而如果 test() 是一個(gè)空函數(shù)(Free function —— 不附加到任何類),將會(huì)出現(xiàn)一個(gè)編譯錯(cuò)誤。
  • 『 it 』為原字符串本身『 Boss 』
  • 『 result 』是數(shù)字 69,我們已經(jīng)從區(qū)間返回賦值

我們用表格更直觀的作顯示:

操作符 接收者(this) 傳參(it) 返回值(result)
let this@Myclass String( "Boss" ) Int( 69 )

依此類推:我們可以這段代碼為其余的功能做類似的事情。

以下是測(cè)試操作符通用的代碼,你可以使用 let、run、apply、also 中任何的操作符替換 xxx。

class MyClass {
    fun test() {
        val str: String = "Boss"
        val result = str.xxx {
             print(this) // 接收者
             print(it) // 參數(shù)
             69 //區(qū)間返回值
        }
        print(result)
    }
}

返回值為:

操作符 接收者(this) 傳參(it) 賦值(result)
T.let() this@Myclass String( "Boss" ) Int( 69 )
T.run() String( "Boss" ) 編譯錯(cuò)誤 Int( 69 )
T.apply() String( "Boss" ) 編譯錯(cuò)誤 String( "Boss" )
T.also() this@Myclass String( "Boss" ) String( "Boss" )

with 與 also 操作符在使用上有一些細(xì)微的差異,例如:

class MyClass {
    fun test() {
        val str: String = "Boss"
        val result = with(str) {
             print(this) // 接收者
            // print(it) // 參數(shù)
            69 //區(qū)間返回值
        }
        print(result)
    }
}

class MyClass {
    fun test() {
        val str: String = "Boss"
        val result = run  {
            print(this) // 接收者
            // print(it) // 參數(shù)
            69 //區(qū)間返回值
        }
         print(result)
    }
}
操作符 接收者(this) 傳參(it) 返回值(result)
run() this@Myclass 編譯錯(cuò)誤 Int( 69 )
with(T) String("Boss") 編譯錯(cuò)誤 Int( 69 )

合二為一:

操作符 接收者(this) 傳參(it) 返回值(result)
T.let() this@Myclass String( "Boss" ) Int( 69 )
T.run() String( "Boss" ) 編譯錯(cuò)誤 Int( 69 )
run() this@Myclass 編譯錯(cuò)誤 Int( 69 )
with(T) String( "Boss" ) 編譯錯(cuò)誤 Int( 69 )
T.apply() String( "Boss" ) 編譯錯(cuò)誤 String( "Boss" )
T.also() this@Myclass String( "Boss" ) String( "Boss" )

而關(guān)于什么時(shí)候我們應(yīng)該用到什么操作符,可以參考這個(gè)圖:

Function_selections
Function_selections

參考文章:

  1. Mastering Kotlin standard functions: run, with, let, also and apply
  2. The difference between Kotlin’s functions: ‘let’, ‘a(chǎn)pply’, ‘with’, ‘run’ and ‘a(chǎn)lso’
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容