Kotlin中run, with, let, also and apply使用方法

1、普通寫法和擴(kuò)展函數(shù)

with和T.run 看起來(lái)很相似,并且它們的功能也類似。

with(webview.setting){
    javaScriptEnabled = true
    databaseEnabled = true
}
webview.settings.run {
    javaScriptEnabled = true
    databaseEnabled = true
}

如果webview.settings為空呢?

with(webview.settings) {
      this?.javaScriptEnabled = true
      this?.databaseEnabled = true
   }
}
webview.settings?.run {
    javaScriptEnabled = true
    databaseEnabled = true
}

這時(shí)候,使用T.run擴(kuò)展功能是比較好的,因?yàn)槲覀兛梢栽谑褂们皺z查可空性。

2、this vs it

string?.run {
      println("The length of this String is $length")
}

string?.let {
      println("The length of this String is ${it.length}")
}

如果你查看T.run的函數(shù)簽名,你會(huì)發(fā)現(xiàn)T.run只是作為擴(kuò)展函數(shù)調(diào)用block:T.()。因此,所有的范圍內(nèi),T被稱為this。在編程時(shí),this在大部分情況下可以省略。因此,在上面的例子中,我們可以用$length代替"${this.length}"。

而對(duì)于T.let的函數(shù)簽名,你會(huì)發(fā)現(xiàn)T.let正在傳遞它自己,即block:(T)。因此,這就像一個(gè)lambda參數(shù)傳遞。在它的作用域范圍內(nèi)被稱為it。

查看所有的屬性

讓我們來(lái)說(shuō)明T.apply功能

① 它是一個(gè)擴(kuò)展函數(shù)
② this作為參數(shù)傳遞
③ 返回this(即它本身)

使用方法:

//通常寫法
fun createInstance(args:Bundle):MyFragment{
    val fragment=MyFragment()
    fragment.arguments=args
    return fragment
}
//改進(jìn)后的寫法
fun createInstance(args:Bundle)=MyFragment().apply{arguments=args}

或者我們也可以創(chuàng)建無(wú)鏈對(duì)象

//通常寫法
fun createIntent(datas:String,actionData:String):Intent{
    val intent=Intent()
    intent.action=actionData
    intent.data=Uri.parse(datas)
    return intent
}
//改進(jìn)后的寫法
fun createIntent(datas:String,actionData:String)=
                  Intent().apply{action=actionData}
                          .apply{data=datas}
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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