let,apply,with,run函数区别

let

默认当前对象闭包的 it 参数,返回值是函数里面最后一行,或者指定return

fun testLet():Int {
    "testLet".let {
        println(it)
        println(it)
        println(it)
        return 1
    }
}

apply

调用某对象的 apply 函数,在函数范围内,可以调用该对象的任意函数,返回值是该对象。

fun testApply() {
    ArrayList<String>().apply {
        add("apply1")
        add("apply2")
        add("apply3")
    }.let { print(it) }
}

with

返回值是最后一行,函数范围中可以调用对象方法。像 let 和 apply 结合

fun testWith() {
    with(ArrayList<String>()) {
        add("testWith")
        add("testWith")
        add("testWith")
        this
    }.let { println(it) }
}

run

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

fun testRun() {
    "testRun".run {
        println("this = " + this)
    }.let { println(it) }
}

猜你喜欢

转载自blog.csdn.net/qq_23621841/article/details/80990048