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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,841評論 0 10
  • 每次丟掉什么東西后,我都會有種悵然若失的感覺,就會無比的沮喪。說真的,我他媽也不知道自己在難過些什么,可就是很傷...
    GC龔成閱讀 228評論 0 0
  • 感謝前Linkedln新媒體負責(zé)人鄒瞳老師帶來的分享! 提要建議:①確定清晰的目標:想做10w的號,目標先定在50...
    木子一撇一捺閱讀 926評論 0 8
  • 他叫白亞默,一個不能說改變我一生,但至少是影響了我一生的人。 與他相識,是在七年前,一個很平常的夏日午后。 我在路...
    邢雪橋閱讀 1,601評論 2 1
  • 朋友養(yǎng)的梔子花開了,拍了照片發(fā)給我,與我分享梔子花的白潔與清香。 “這是我這輩子養(yǎng)的所有梔子花里面第一次開花的,真...
    嘉文莫爾閱讀 497評論 0 2

友情鏈接更多精彩內(nèi)容