Member-only story
Exploring Scope Functions in Kotlin
let, run, apply, with, and also
Introduction
The Kotlin functions whose sole purpose is to execute a block of code via a given lambda expression on an object by creating a temporary scope are known as Kotlin scope functions. These functions make code more readable, clear, and concise. There are five types of scope functions in Kotlin:
let
run
apply
with
also
In the following sections, we’re going to dig more into each of these functions at which point you might start to notice all of them are very similar, but the key is to understand the functions clearly to decide which function to use when the time comes.
Let’s consider the following data class to use with each of the scope functions and understand how the execution works.
data class Movie(
var name: String,
val id: Int,
val posterUrl: String
) {
fun updateName(_name: String) {
name = _name
}
}
let
let is one of the very commonly used scope functions, let’s get started by looking at the syntax of the function:
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
let
is nothing but an extension function on a generic type that takes lambda as a parameter. Whereas the return type of it is nothing but the return type of the parameter lambda, usually it’s the last statement of the lambda. Inside the block, we can refer to the object as it
. Let’s consider the following example:
fun updateMovieName(movie: Movie?): Movie?{
return movie?.let {
it.updateName("Dune - Part 1")
println(it)
it
}
}
In the above example, we’ve used let
with Elvis operator for null safety and we’ve returned the updated movie object as the return type of the updateMovieName
function. If the last statement is…