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)
}
}