kotlin

kotlin:四大函数表达式

2018-08-12  本文已影响71人  宋song一

1.Apply(使用this代表当前对象,返回值是当前对象)

* 1.任意对象 任意类型都有apply扩展函数
* 2.apply函数参数是函数类型 带接受者(T)的函数字面值
* 3.apply函数返回值是当前对象本身

源码如下

public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

2.Let(使用it代表当前对象,返回值是表达式最后一行)

源码

public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

3.With(使用this代表当前对象,返回值是最后一行)

4.Run(代码块)

源码

public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}
上一篇 下一篇

猜你喜欢

热点阅读