Learn Kotlin —  apply vs with

Learn Kotlin%E2%80%8A%E2%80%94%E2%80%8Aapply Vs with

apply vs with

There are many great features available in Kotlin, we can take advantage of all these features to write a better application in Kotlin. Among all those features, apply and with are important features. We must know when to use which one.

When to use “apply”, when to use “with”?

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. Apply() can do much more than simply setting properties of course. It is a transformation function, capable of evaluating complex logic before returning. In 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.

Let's see the differences between “apply” and “with”.

There are mainly two differences:

  • 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 of apply

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

Example of with

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