Android我爱编程

Kotlin apply vs with

2018-06-15  本文已影响60人  假装在去天使之城的路上

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

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

上一篇 下一篇

猜你喜欢

热点阅读