手动实现Kotlin内置函数

内置函数持有值返回值异同点使用场景
T.applythisthis
T.alsoitthis==apply,持有值不同
T.letitreturn判空+空合并操作符
T.runthisreturn
with(T)thisreturn==run,调用方式不同
takeIfitture=this false=null空合并操作符
takeUnlessitture=null false=thistakeIf相反空合并操作符+string.isNullOrBlack

apply

fun <T> T.myApply(action: T.() -> Unit): T {
    //持有this ,return this
    this.action()
    return this
}

let

fun <T, R> T.myLet(action: (T) -> R): R {
    //持有it ,return this.action(it)类型
    return action(this)
}

run

fun <T, R> T.myRun(action: T.() -> R): R {
    //持有this ,return this.action()类型
    return this.action()
}

also

fun <T> T.myAlso(action: (T) -> Unit): T {
    //持有it ,return this
    action(this)
    return this
}

with

fun <T, R> myWith(ob: T, action: T.() -> R): R {
    //持有ob = this ,return ob.action()类型
    return ob.action()
}

takeIf

fun <T> T.myTakeIf(action: (T) -> Boolean): T? {
    //持有it ,return this.action(it) = [true this类型 ,false null类型]
    val isTrue = action(this)
    return if (isTrue) this else null
}

takeUnless

fun <T> T.myTakeUnless(action: (T) -> Boolean): T? {
    //持有it ,return this.action(it) = [false this类型 ,true null类型]
    val isTrue = action(this)
    return if (!isTrue) this else null
}

其他

fun <T> T.myTake(action: (T) -> Boolean): Boolean {
    //持有it,return this.action(it)的boolean类型
    return action(this)
}
fun <T, R> T.myCustom(action: T.(T) -> R): R {
    //持有this ,return action(this)类型
    return this.action(this)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值