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