Kotlin 標準庫中run、let、also、apply、with的用法和區(qū)別

run 函數(shù)

定義


inline fun <R> run(block: () -> R): R         //1
Calls the specified function block and returns its result.


inline fun <T, R> T.run(block: T.() -> R): R  //2
Calls the specified function block with this value as its receiver and returns its result.

第一種使用:直接使用run函數(shù)返回其結果(最后一行的結果)


fun runTest() {
    val a = run {
        "abc"
        1
    }
    val b = run {
        1
        2
        "abc"
    }
    println(a)
    println(b)
}

打印結果:

1

abc

第二種使用:調用某個對象(該對象作為接收者)的run函數(shù)并返回結果


fun runTestWithT() {
    val a = 1.run {
        "$this 和 abc"
    }
    println(a)
}  

打印結果:

1 和 abc

let 函數(shù)

定義


inline fun <T, R> T.let(block: (T) -> R): R
Calls the specified function block with this value as its argument and returns its result.

使用:調用某個對象(該對象作為函數(shù)的參數(shù))的let的函數(shù)并返回結果


fun letTest() {
    val let = "abc".let {
        println(it)
        1
    }
    println(let)
}

打印結果:

abc

1

also 函數(shù)

定義


inline fun <T> T.also(block: (T) -> Unit): T
Calls the specified function block with this value as its argument and returns this value.

使用: 調用某一對象的also 函數(shù)(該對象作為函數(shù)參數(shù))并返回改對象


fun alsoTest() {
    val also = "abc".also {
        println(it)
    }
    println(also)
}

打印結果:

abc
abc

apply 函數(shù)

定義


inline fun <T> T.apply(block: T.() -> Unit): T
Calls the specified function block with this value as its receiver and returns this value.

使用:調用對象(該對象作為接收者)的apply函數(shù)并返回該對象


fun applyTest(){
    val apply ="abc".apply {
        println(this)
    }
    println(apply)
}

打印結果:

abc

abc

with 函數(shù)

定義


inline fun <T, R> with(receiver: T, block: T.() -> R): R
Calls the specified function block with the given receiver as its receiver and returns its result.

使用:使用給定接收器作為接收器調用with函數(shù)并返回其結果


fun withTest() {
    val with = with("abc") {
        println(this)
        1111
    }
    println(with)
}

打印結果:

abc
1111

with 函數(shù)的使用形式與其他幾個函數(shù)的類型不一樣

with 函數(shù)重要的一個作用是使用它實現(xiàn)構建者模式

舉個例子


class Student(builder: Builder) {

    var name: String = ""
    var age = 1

    init {
        name = builder.name
        age = builder.age
    }

    class Builder {
        var name: String = ""
        var age: Int = 0
        fun builder(): Student = Student(this)
    }
}

使用with函數(shù)構建:


fun withTest() {

    val student = with(Student.Builder()) {
        this.age = 18
        this.name = "marry"
        builder()
    }
    println("name: ${student.name},age:${student.age}")
}

打印結果:


name: marry,age:18

看了上面的幾個簡單的使用,我們可能就能從幾個函數(shù)的定義可以看出他們區(qū)別:

從返回結果不同來看

  • 返回其他結果run ,letwith

  • 返回自身結果also ,apply

從對象調用的作用來看

  • 調用者作為參數(shù)let,also

  • 調用者作為接收者run,with,apply

參考:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/index.html

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容