Kotlin apply vs with

apply

By definition, apply accepts a function, and sets its scope to that of the object on which apply has been invoked. This means that no explicit reference to the object is needed.

It is a transformation function, capable of evaluating complex logic before returning.

At the end, the function simply returns the same object (with the added changes), so one can keep using it on the same line of code.

apply VS with

  • apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases the instance will become this within a block.
  • apply returns the receiver and with returns a result of the last expression within its block.

  • Usually you use apply when you need to do something with an object and return it. And when you need to perform some operations on an object and return some other object you can use with.

Example

fun getDeveloper(): Developer {
    return Developer().apply {
        developerName = "Amit Shekhar"
        developerAge = 22
    }
}

companion object {
    @JvmStatic
    fun newInstance(param1: String, param2: String) =
            IDCameraFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
}

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

Links

Learn Kotlin —  apply vs with

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,900评论 0 10
  • 每次丢掉什么东西后,我都会有种怅然若失的感觉,就会无比的沮丧。说真的,我他妈也不知道自己在难过些什么,可就是很伤...
    GC龚成阅读 234评论 0 0
  • 感谢前Linkedln新媒体负责人邹瞳老师带来的分享! 提要建议:①确定清晰的目标:想做10w的号,目标先定在50...
    木子一撇一捺阅读 935评论 0 8
  • 他叫白亚默,一个不能说改变我一生,但至少是影响了我一生的人。 与他相识,是在七年前,一个很平常的夏日午后。 我在路...
    邢雪桥阅读 1,615评论 2 1
  • 朋友养的栀子花开了,拍了照片发给我,与我分享栀子花的白洁与清香。 “这是我这辈子养的所有栀子花里面第一次开花的,真...
    嘉文莫尔阅读 511评论 0 2

友情链接更多精彩内容