前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin 中的 appy和with方法

Kotlin 中的 appy和with方法

作者头像
一个会写诗的程序员
发布2019-07-01 11:00:40
7000
发布2019-07-01 11:00:40
举报

Kotlin 中的 appy和with方法

apply

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

实现:

代码语言:javascript
复制
public inline fun <T> T.apply(block: T.() -> Unit): T { 
    block(); 
    return this 
}

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

代码语言:javascript
复制
//调用方法, 省去了 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.

它的实现代码也只有一行

代码语言:javascript
复制
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的返回类型相同

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.06.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Kotlin 中的 appy和with方法
    • apply
      • with
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档