Kotlin Standard Functions: apply, also, let, with, and run

Kotlin has provided several powerful functions in Standard.kt. Let’s go through them here quickly.

apply()

The apply() function passes the context object as a receiver, and returns the object itself. We can use it to configure an object after creation, e.g.:

val foo = Foo().apply {
    this.field = initialValue
}

also()

The apply() function passes the context object as a parameter, and returns the object itself. We can use it to do some additional effects to the object, e.g.:

val foo = Foo().also {
    doSomething(it)
}

let()

The let() function passes the context object as a parameter, and returns the result of the lambda function. We can use it to execute some code on a nullable object, e.g.:

val result = nullableObject?.let {
    it.doSomething()
}

We can also use it to define a variable within the scope and prevent it from leaking out, e.g.:

val result = getReference().let {
    it.doSomething()
}
// the reference is no longer visible here

with()

The with() function it the only non-extension function here. It passes the context object as a receiver, and returns the result of the lambda function. We can use it to group function calls on an object, e.g.:

with(view) {
  alpha = 0.0F
  visibility = View.VISIBLE
}

run()

The run() function passes the context object as a receiver, and returns the result of the lambda function. We can use it to configure an object and compute the result, e.g.:

val result = Foo().run {
  this.field = initialValue
  this.doSomething()
}

We can also use it to group function calls on an object, e.g.:

view.run {
  alpha = 0.0F
  visibility = View.VISIBLE
}

That’s it! All these are just regular functions, but they can be easily combined to make the code nicer.


See also

comments powered by Disqus