Kotlin 中的 appy和with方法

Kotlin 中的 appy和with方法

apply

apply:Calls the specified function block with this value as its receiver and returns this value.

实现:

public inline fun <T> T.apply(block: T.() -> Unit): T { 
    block(); 
    return this 
}

apply为高阶函数,它接受一个参数block,类型为 T.() -> Unit ( function-with-receiver)
在apply的函数体内,调用了传入的block这个函数,然后返回调用apply函数的对象实例。

//调用方法, 省去了 this
fun getDeveloper(): Developer {
    return Developer().apply {
        developerName = "Amit Shekhar"
        developerAge = 22
    }
}

with

Calls the specified function block with the given receiver as its receiver and returns its result.

它的实现代码也只有一行

public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

with为高阶函数,接收两个参数:receiver,类型为T,block 类型为 T.() -> R,为 function-with-receiver type,只能被T类型的对象调用.

同样,在block方法体内,可以通过this来调用到receiver。

with返回的类型为R,和block的返回类型相同

fun getPersonFromDeveloper(developer: Developer): Person {
    return with(developer) {
        Person(developerName, developerAge)
    }
}

参考:
learn kotlin apply vs with
what is a receiver in kotlin
What is a purpose of Lambda's with Receiver?
https://www.jianshu.com/p/22c743dca2d4


Kotlin 开发者社区

国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI天才研究院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值