Kotlin 中的 appy和with方法

作者: 光剑书架上的书 | 来源:发表于2019-06-30 23:41 被阅读8次

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、函数式编程、编程思想等相关主题。
Kotlin 开发者社区 QRCode.jpg

相关文章

  • Kotlin 中的 appy和with方法

    Kotlin 中的 appy和with方法 apply apply:Calls the specified fun...

  • Kotlin 什么是幕后字段?

    上篇文章我们了解了Kotlin中的各种类,从Kotlin的类开始说起,而类中则有属性和方法,Kotlin 中的类属...

  • kotlin 基础 Companion Objects 20

    在 kotlin 中没有静态方法和属性,我们想要调用类的方法时候,kotlin给我们提供 componion ob...

  • kotlin中的属性和方法

    1,快捷键:Java中是control+回车产生setter和getter方法,问题:什么时候需要重写set,ge...

  • Kotlin学习之定义函数

    Kotlin学习之定义函数 @(Kotlin学习) 一、定义函数 Kotlin中的函数比Java中的方法更灵活,用...

  • kotlin接口

    kotlin中的接口与Java8中的类似,既包含方法也包含属性。方法包括抽象方法和普通方法,属性包含抽象属性和普通...

  • kotlin 之 类、对象和接口

    定义类继承结构 Kotlin中的接口 Kotlin的接口与Java 8 中的相似:它们可以包含抽象方法(方法=函数...

  • 12.枚举

    由enum修饰的类 kotlin中枚举类可以有构造器以及成员方法 kotlin中enum类提供一些内置成员属性和方...

  • Kotlin 笔记(一) 基础知识点--java对比

    创建对象 类型声明 字符串模板 方法 Kotlin 特性 : 函数参数默认值和可变参数 对Kotlin函数中的某个...

  • Android kotlin静态属性、静态方法

    Kotlin类不支持静态方法和成员,但Kotlin支持全局函数和变量,因此我们可以直接使用全局函数和变量来代替类中...

网友评论

    本文标题:Kotlin 中的 appy和with方法

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