美文网首页
Kotlin之let,apply,with,run函数区别

Kotlin之let,apply,with,run函数区别

作者: 椰子 | 来源:发表于2018-04-23 23:53 被阅读112次

    let

    首先let()的定义是这样的,默认当前这个对象作为闭包的it参数,返回值是函数里面最后一行,或者指定return
    代码示例:

    fun testLet(): Int {
        // fun <T, R> T.let(f: (T) -> R): R { f(this)}
        "testLet".let {
            println(it)
            println(it)
            println(it)
            return 1
        }
    }
    //运行结果
    //testLet
    //testLet
    //testLet
    

    apply

    apply函数是这样的,调用某对象的apply函数,在函数范围内,可以任意调用该对象的任意方法,并返回该对象
    代码示例:

    fun testApply() {
        // fun <T> T.apply(f: T.() -> Unit): T { f(); return this }
        ArrayList<String>().apply {
            add("testApply")
            add("testApply")
            add("testApply")
            println("this = " + this)
        }.let { println(it) }
    }
    
    // 运行结果
    // this = [testApply, testApply, testApply]
    // [testApply, testApply, testApply]
    

    with

    with函数是一个单独的函数,并不是Kotlin中的extension,所以调用方式有点不一样,返回是最后一行,然后可以直接调用对象的方法,感觉像是let和apply的结合。
    代码示例:

    fun testWith() {
        // fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
        with(ArrayList<String>()) {
            add("testWith")
            add("testWith")
            add("testWith")
            println("this = " + this)
        }.let { println(it) }
    }
    // 运行结果
    // this = [testWith, testWith, testWith]
    // kotlin.Unit
    

    run

    run函数和apply函数很像,只不过run函数是使用最后一行的返回,apply返回当前自己的对象。
    代码示例:

    fun testRun() {
        // fun <T, R> T.run(f: T.() -> R): R = f()
        "testRun".run {
            println("this = " + this)
        }.let { println(it) }
    }
    // 运行结果
    // this = testRun
    // kotlin.Unit
    

    Kotlin之let,apply,with,run函数区别

    相关文章

      网友评论

          本文标题:Kotlin之let,apply,with,run函数区别

          本文链接:https://www.haomeiwen.com/subject/oavekxtx.html