美文网首页kotlin
kotlin let、run、with、also、apply函数

kotlin let、run、with、also、apply函数

作者: leoryzhu | 来源:发表于2019-10-04 09:45 被阅读0次

一、let

当前对象:it
返回值:闭包

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

二、run

当前对象:this或省略
返回值:闭包

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

三、also

当前对象:it
返回值:this

@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
}

四、apply

当前对象:this和省略
返回值:this

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

五、with

当前对象:this或省略
返回对象:闭包

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

相关文章

网友评论

    本文标题:kotlin let、run、with、also、apply函数

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