kotlin apply run also with let函數(shù)

apply

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 *
 * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#apply).
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

我們從源碼中可以知道 apply接受一個(gè)對象,返回一個(gè)對象崩瓤。閉包中使用(this)指代對象
一般使用于成員對象的操作
官方文檔對其解釋為 apply the following assignments to the object.

class StudyOne {
    var karl: String ?= null

    var karlTwo: String ?= null
}
fun main(args: Array<String>) {
    val studyOne = StudyOne().apply {
        this.karl = "aa"
        this.karlTwo = "bb"
    }
    println("studyOne: ${studyOne.karl}") 
    println("studyOne: ${studyOne.karlTwo}")
}
//運(yùn)行結(jié)果
//aa
//bb

參考文檔: apply

run

/**
 * Calls the specified function [block] with `this` value as its receiver and returns its result.
 *
 * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#run).
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

我們發(fā)現(xiàn) run跟apply的差別只是apply返回對象本身伪货,run一個(gè)返回lamda表達(dá)式(跟run做同樣事情的還有with, let)
run一般用于初始化和返回值的計(jì)算

fun testRun() {
  studyOne.run {
        println("karl")
    }
}
// 輸出結(jié)果
//karl

另一個(gè)run 非擴(kuò)展性功能run

@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

執(zhí)行閉包们衙,返回閉包結(jié)果

fun main(args: Array<String>) {
    val studyOne = run {
            StudyOne()
        }
    println(studyOne)
}
//運(yùn)行結(jié)果
//StudyOne@7a81197d

參考文檔: run

also

/**
 * Calls the specified function [block] with `this` value as its argument and returns `this` value.
 *
 * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#also).
 */
@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
}

接受一個(gè)對象,返回一個(gè)對象本身,一般使用于不影響對象本身做某些事

fun main(args: Array<String>) {
    val numbers = mutableListOf("one", "two", "three")
    val alsoTest = numbers.also {
        println("kotlin真好用")
        println("c: $it")
    }
        .add("four")
    println("c: $numbers")
}
//運(yùn)行結(jié)果
//kotlin真好用
//c: [one, two, three]
//c: [one, two, three, four]

參考文檔: also

with

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 *
 * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

非擴(kuò)展功能,接受一個(gè)對象碱呼,返回lamda表達(dá)式結(jié)果蒙挑,可以理解為 對這個(gè)對象執(zhí)行以下操作

fun main(args: Array<String>) {
    val numbers = mutableListOf("one", "two", "three")
    with(numbers) {
        this.add("karl")
        this.add("帥的起飛")
    }
    println("numbers: $numbers")
}
//運(yùn)行結(jié)果
//numbers: [one, two, three, karl, 帥的起飛]

參考文檔: with

let

/**
 * Calls the specified function [block] with `this` value as its argument and returns its result.
 *
 * For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#let).
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

接受一個(gè)對象,返回lamda表達(dá)式結(jié)果,或者指定return

fun main(args: Array<String>) {
    val numbers = mutableListOf("one", "two", "three")
    fun testLet(): Int {
        numbers.let {
            return if (Random().nextBoolean()) {
                it.add("five")
                println(it)
                1
            } else {
                it.add("six")
                println(it)
                2
            }
        }
    }
}

?.let 對象不為空時(shí)執(zhí)行

參考文檔: let

taskIf

滿足block中條件愚臀,則返回當(dāng)前值忆蚀,否則返回null,block的返回值Boolean類型

takeUnless

不滿足block中條件姑裂,則返回當(dāng)前值馋袜,否則返回null,block的返回值Boolean類型

總結(jié)

執(zhí)行非空對象lamda: ?.let
判斷局部范圍變化: let
對象配置: apply
對象配置和計(jì)算處理: run
運(yùn)行需要的lamda表達(dá)式: 非擴(kuò)展功能 run
附加: also
對象分組調(diào)用: with

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末舶斧,一起剝皮案震驚了整個(gè)濱河市欣鳖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌茴厉,老刑警劉巖泽台,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件什荣,死亡現(xiàn)場離奇詭異,居然都是意外死亡怀酷,警方通過查閱死者的電腦和手機(jī)稻爬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來胰坟,“玉大人因篇,你說我怎么就攤上這事”屎幔” “怎么了竞滓?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吹缔。 經(jīng)常有香客問我商佑,道長,這世上最難降的妖魔是什么厢塘? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任茶没,我火速辦了婚禮,結(jié)果婚禮上晚碾,老公的妹妹穿的比我還像新娘抓半。我一直安慰自己,他們只是感情好格嘁,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布笛求。 她就那樣靜靜地躺著,像睡著了一般糕簿。 火紅的嫁衣襯著肌膚如雪探入。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天懂诗,我揣著相機(jī)與錄音蜂嗽,去河邊找鬼。 笑死殃恒,一個(gè)胖子當(dāng)著我的面吹牛植旧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播离唐,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼隆嗅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了侯繁?” 一聲冷哼從身側(cè)響起胖喳,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎贮竟,沒想到半個(gè)月后丽焊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體较剃,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年技健,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了写穴。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡雌贱,死狀恐怖啊送,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情欣孤,我是刑警寧澤馋没,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站降传,受9級(jí)特大地震影響篷朵,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜婆排,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一声旺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧段只,春花似錦腮猖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鹦赎,卻和暖如春谍椅,著一層夾襖步出監(jiān)牢的瞬間误堡,已是汗流浹背古话。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锁施,地道東北人陪踩。 一個(gè)月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像悉抵,于是被迫代替她去往敵國和親肩狂。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評論 2 354