Exploring Scope Functions in Kotlin

let, run, apply, with, and also

Siva Ganesh Kantamani
4 min readAug 22, 2024
Photo by Carl Tronders on Unsplash

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:

  1. let
  2. run
  3. apply
  4. with
  5. 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.

overview of scope functions, image source: https://kotlinlang.org/docs/scope-functions.html#function-selection

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

--

--