Sep 15, 2021
apply vs with
we use apply when we need to perform some operation on a object and return it.
We use with when we need to perform some operation on a object and return some other object.
Difference between apply vs with
apply function will take instance as an receiver while with function we need to pass instance as an argument.But in both case the instance will be refered with this inside the block
Example of apply
fun getDeveloper(): Developer {
return Developer().apply {
developerName = "Pandiyan"
developerAge = 22
}
}
Example of with
fun getPersonFromDeveloper(developer: Developer): Person {
return with(developer) {
Person(developerName, developerAge)
}
}