Kotlin標(biāo)準(zhǔn)函數(shù)run,with,let,also和apply的使用和區(qū)別

選擇哪種函數(shù)

1.讓我們看看源碼中是如何定義的

/**
 * Calls the specified function [block] and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

/**
 * Calls the specified function [block] with `this` value as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

/**
 * Calls the specified function [block] with `this` value as its argument and returns `this` value.
 */
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

/**
 * Calls the specified function [block] with `this` value as its argument and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

看每個(gè)方法的返回值類型
apply,also返回的是它本身類型
run嘀倒,with屈留,let返回的是代碼塊最后一行的返回值類型

2.各個(gè)函數(shù)的應(yīng)用場景

2.1 T.apply應(yīng)用場景
//普通方法
fun createIntent(): Intent {
        val intent = Intent()
        intent.putExtra("nameFirst", "firstValue")
        intent.putExtra("nameSecond", "secondValue")
        return intent
}

//通過apply函數(shù)
fun createIntentByApply(): Intent =
            Intent().apply {
                putExtra("nameFirst", "firstValue")
                putExtra("nameSecond", "secondValue")
            }

//通過apply函數(shù)鏈?zhǔn)秸{(diào)用
fun createIntentByChainedApply(): Intent =
            Intent().apply { putExtra("nameFirst", "firstValue") }
                    .apply { putExtra("nameSecond", "secondValue") }
2.2 T.also函數(shù)
"abc".also {
    print("The String is $it") // "abc"
    it.reversed()
}.also {
    print("The reverse String is $it") // "abc"
    it.length
}.also {
    println("The length of the String is $it") // "abc"
}
2.3 T.let函數(shù)
"abc".let {
    println("The String is $it") // "abc"
    it.reversed() 
}.let {
    println("The reverse String is $it") // "cba"
    it.length  
}.let {
    println("The length of the String is $it") // 3
}

和also函數(shù)相比返回值不同局冰,T.let返回的是作用域最后一個(gè)對(duì)象(可和自身對(duì)象不同),
T.also返回的都是原來自身對(duì)象灌危。

兩者結(jié)合使用場景
//原始函數(shù)
fun makeDir(path: String): File  {
    val result = File(path)
    result.mkdirs()
    return result
}

//通過let和also的鏈?zhǔn)秸{(diào)用改進(jìn)后的函數(shù)
fun makeDir(path: String) = path.let{ File(it) }.also{ it.mkdirs() }
2.4 run函數(shù)使用場景
run {
    if (islogin) loginDialog else getAwardDialog
}.show()
2.5 with函數(shù)使用場景
with(webView.settings){
    javaScriptEnabled = true
    databaseEnabled = true
}
2.6 T.run函數(shù)使用場景
//此時(shí)run函數(shù)比上面例子要更好康二,因?yàn)樵谡{(diào)用函數(shù)之前進(jìn)行null檢查
webView.settings?.run { 
    javaScriptEnabled = true
    databaseEnabled = true
}

參考文獻(xiàn)

https://juejin.im/entry/5aaaa9156fb9a028dc40c1b2

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市勇蝙,隨后出現(xiàn)的幾起案子沫勿,更是在濱河造成了極大的恐慌,老刑警劉巖味混,帶你破解...
    沈念sama閱讀 218,036評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件产雹,死亡現(xiàn)場離奇詭異,居然都是意外死亡翁锡,警方通過查閱死者的電腦和手機(jī)蔓挖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來馆衔,“玉大人瘟判,你說我怎么就攤上這事〗抢#” “怎么了拷获?”我有些...
    開封第一講書人閱讀 164,411評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長开镣。 經(jīng)常有香客問我刀诬,道長,這世上最難降的妖魔是什么邪财? 我笑而不...
    開封第一講書人閱讀 58,622評(píng)論 1 293
  • 正文 為了忘掉前任陕壹,我火速辦了婚禮,結(jié)果婚禮上树埠,老公的妹妹穿的比我還像新娘糠馆。我一直安慰自己,他們只是感情好怎憋,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評(píng)論 6 392
  • 文/花漫 我一把揭開白布又碌。 她就那樣靜靜地躺著,像睡著了一般绊袋。 火紅的嫁衣襯著肌膚如雪毕匀。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評(píng)論 1 304
  • 那天癌别,我揣著相機(jī)與錄音皂岔,去河邊找鬼。 笑死展姐,一個(gè)胖子當(dāng)著我的面吹牛躁垛,可吹牛的內(nèi)容都是我干的剖毯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼教馆,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼逊谋!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起土铺,我...
    開封第一講書人閱讀 39,200評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤胶滋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后舒憾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體镀钓,經(jīng)...
    沈念sama閱讀 45,644評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評(píng)論 3 336
  • 正文 我和宋清朗相戀三年镀迂,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唤蔗。...
    茶點(diǎn)故事閱讀 39,953評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡探遵,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出妓柜,到底是詐尸還是另有隱情箱季,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評(píng)論 5 346
  • 正文 年R本政府宣布棍掐,位于F島的核電站藏雏,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏作煌。R本人自食惡果不足惜掘殴,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望粟誓。 院中可真熱鬧奏寨,春花似錦、人聲如沸鹰服。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽悲酷。三九已至套菜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間设易,已是汗流浹背逗柴。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留亡嫌,地道東北人嚎于。 一個(gè)月前我還...
    沈念sama閱讀 48,119評(píng)論 3 370
  • 正文 我出身青樓掘而,卻偏偏與公主長得像,于是被迫代替她去往敵國和親于购。 傳聞我的和親對(duì)象是個(gè)殘疾皇子袍睡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容