Kotlin Scope Functions Explained: let, run, with, apply & also

When developing Android applications using Kotlin and Jetpack Compose, we frequently need to perform multiple operations on an object.

For example, we might need to:

  • Configure a user object
  • Validate nullable data
  • Initialize a ViewModel-related model
  • Process an API response
  • Update application settings
  • Transform data
  • Log debugging information
  • Configure Android UI components

Kotlin provides five powerful functions called scope functions that help us write these operations more concisely.

The five Kotlin scope functions are:

  1. let
  2. run
  3. with
  4. apply
  5. also

Although these functions may look similar, they differ in how they reference an object and what they return.

Understanding these differences is essential for writing clean, readable Kotlin code.

In this tutorial, we’ll explore each scope function step by step with practical examples and Android use cases.


What You’ll Learn

By the end of this tutorial, you’ll understand:

  • What Kotlin scope functions are
  • Why scope functions are useful
  • Kotlin let() with examples
  • Kotlin run() with examples
  • Kotlin with() with examples
  • Kotlin apply() with examples
  • Kotlin also() with examples
  • Differences between this and it
  • Scope function return values
  • Scope functions with nullable objects
  • Chaining scope functions
  • Common Android use cases
  • Jetpack Compose integration
  • Common mistakes and best practices

Let’s begin!


1. What Are Scope Functions in Kotlin?

Scope functions are Kotlin standard library functions that execute a block of code in the context of an object.

They allow us to temporarily access an object without repeatedly writing its variable name.

Consider the following example.

Without Scope Functions

data class User(
    var name: String,
    var age: Int,
    var city: String
)

fun main() {

    val user = User("", 0, "")

    user.name = "Alex"
    user.age = 25
    user.city = "Hyderabad"

    println(user)
}

Output:

User(name=Alex, age=25, city=Hyderabad)

We repeatedly reference the user variable.

Kotlin scope functions can make this code more concise.

With apply()

val user = User("", 0, "").apply {

    name = "Alex"
    age = 25
    city = "Hyderabad"
}

println(user)

The result is the same, but the code is more compact.

Important

Scope functions do not introduce fundamentally new capabilities.

They provide a convenient way to organize operations on existing objects.


2. Kotlin Scope Functions Comparison Table

Before exploring individual functions, let’s compare them.

FunctionObject ReferenceReturn ValueCommon Use
letitLambda resultNull checks and transformations
runthisLambda resultObject operations and calculations
withthisLambda resultMultiple operations on an object
applythisOriginal objectObject configuration
alsoitOriginal objectLogging and additional actions

The two most important differences are:

1. How the object is referenced

The object can be accessed using this or it.

2. What the function returns

The function can return the original object or the result of its lambda expression.

Once you understand these two concepts, scope functions become much easier to use.


3. Kotlin let() Function

The let() function executes a lambda using the object as its argument.

Inside the lambda, the object is usually referenced using it.

Syntax

objectName.let {
    // Access object using it
}

Example

fun main() {

    val name = "Kotlin"

    name.let {
        println("Welcome to $it")
    }
}

Output:

Welcome to Kotlin

Explanation

The String value "Kotlin" becomes the lambda argument.

The keyword it represents that value.

We can also provide a descriptive parameter name.

name.let { language ->
    println("Learning $language")
}

When to Use let()

Use let() when you want to:

  • Work with nullable values
  • Transform an object into another value
  • Introduce a short local scope
  • Pass an object into a calculation
  • Perform an operation using an explicit lambda parameter

4. Kotlin let() with Null Safety

One of the most common uses of let() is handling nullable objects.

Example Without let()

val username: String? = "Alex"

if (username != null) {
    println(username.uppercase())
}

Example with let()

val username: String? = "Alex"

username?.let {
    println(it.uppercase())
}

Output:

ALEX

How It Works

The safe-call operator:

?.

executes let() only when the receiver is not null.

If username is null, the lambda is skipped.

Example with a Null Value

val username: String? = null

username?.let {
    println("Hello $it")
}

No message is printed.

Practical Android Example

val userEmail: String? = "alex@example.com"

userEmail?.let { email ->
    println("Sending email to $email")
}

This pattern is useful when working with nullable values returned by databases, APIs, or application state.

Important

The expression value?.let { ... } returns null when the receiver is null.

Also, calling let() without ?. does not automatically prevent null values from reaching the lambda.


5. Kotlin let() Return Value

The let() function returns the result of the final expression inside its lambda.

Example

fun main() {

    val number = 10

    val result = number.let {
        it * 2
    }

    println(result)
}

Output:

20

String Transformation Example

val name = "android"

val result = name.let {
    it.uppercase()
}

println(result)

Output:

ANDROID

Practical Use

let() is useful when transforming a value into another value while keeping the transformation close to its source.


6. Kotlin run() Function

The run() function executes a block of code in the context of an object.

Unlike let(), the receiver is accessed using this.

Syntax

objectName.run {
    // Access object using this
}

Example

data class Product(
    val name: String,
    val price: Int
)

fun main() {

    val product = Product(
        name = "Android Phone",
        price = 15000
    )

    val description = product.run {
        "$name costs ₹$price"
    }

    println(description)
}

Output:

Android Phone costs ₹15000

Explanation

Inside run(), we can access the object’s properties directly.

Instead of writing:

product.name
product.price

we can write:

name
price

When to Use run()

Use run() when you need to:

  • Perform multiple operations on an object
  • Calculate a result
  • Access several properties
  • Return a computed value

7. Kotlin run() with Multiple Operations

Let’s calculate the final price of a product.

data class Product(
    val name: String,
    val price: Double,
    val discount: Double
)

fun main() {

    val product = Product(
        name = "Keyboard",
        price = 2500.0,
        discount = 10.0
    )

    val finalPrice = product.run {

        val discountAmount = price * discount / 100

        price - discountAmount
    }

    println(finalPrice)
}

Output:

2250.0

Explanation

Inside run():

  1. We calculate the discount amount.
  2. We subtract it from the original price.
  3. The final expression becomes the return value.

Non-Extension run()

Kotlin also provides a standalone run { ... } function.

val result = run {

    val a = 10
    val b = 20

    a + b
}

println(result)

Output:

30

This form is useful when you need a temporary scope that returns a calculated value without requiring a receiver object.


8. Kotlin with() Function

The with() function executes a block of code using a given object as the receiver.

It is similar to run(), but the object is passed as a function argument.

Syntax

with(objectName) {
    // Access object using this
}

Example

data class Student(
    val name: String,
    val age: Int,
    val course: String
)

fun main() {

    val student = Student(
        "Emma",
        22,
        "Android Development"
    )

    with(student) {

        println(name)
        println(age)
        println(course)
    }
}

Output:

Emma
22
Android Development

Explanation

Inside the with() block, the Student object becomes the receiver.

We can directly access its properties.

When to Use with()

Use with() when:

  • An object is already available
  • You need to access several properties
  • You want to perform related operations
  • You want to return a calculated result

9. Kotlin with() Return Value

Like run(), with() returns the result of the final expression.

Example

data class Rectangle(
    val width: Int,
    val height: Int
)

fun main() {

    val rectangle = Rectangle(10, 5)

    val area = with(rectangle) {
        width * height
    }

    println(area)
}

Output:

50

Difference Between run() and with()

Using run():

val area = rectangle.run {
    width * height
}

Using with():

val area = with(rectangle) {
    width * height
}

Both return the same result.

The main difference is their calling syntax.

run() is an extension function, while with() is a regular function that receives the object as an argument.


10. Kotlin apply() Function

The apply() function is commonly used to configure an object.

It accesses the object using this and returns the original object.

Syntax

objectName.apply {
    // Configure object
}

Example

data class User(
    var name: String = "",
    var age: Int = 0,
    var city: String = ""
)

fun main() {

    val user = User().apply {

        name = "Alex"
        age = 28
        city = "Hyderabad"
    }

    println(user)
}

Output:

User(name=Alex, age=28, city=Hyderabad)

Explanation

Inside apply(), we configure the object.

The function returns that same object.

This allows us to assign the configured object directly to a variable.

When to Use apply()

Use apply() for:

  • Object initialization
  • Configuration
  • Setting multiple properties
  • Android View setup
  • Builder-style object configuration

11. Kotlin apply() in Android Development

The apply() function is frequently used in traditional Android development.

Example: Intent Configuration

val intent = Intent(
    context,
    DetailActivity::class.java
).apply {

    putExtra("user_id", 101)

    putExtra("user_name", "Alex")
}

Explanation

The Intent is created and configured in one expression.

The resulting variable contains the configured Intent.

Another Example: TextView Configuration

val textView = TextView(context).apply {

    text = "Welcome to Android"

    textSize = 18f

    setTextColor(Color.BLACK)
}

Why Is This Useful?

Without apply(), we would repeatedly reference the object.

With apply(), initialization becomes more concise.

Jetpack Compose Note

Jetpack Compose typically uses immutable UI parameters and declarative composables instead of manually configuring Views.

However, apply() remains useful for configuring supporting objects and interacting with Android framework APIs.


12. Kotlin also() Function

The also() function executes an additional operation on an object and returns the original object.

The object is referenced using it.

Syntax

objectName.also {
    // Perform additional action
}

Example

fun main() {

    val numbers = mutableListOf(
        10,
        20,
        30
    ).also {

        println("List created: $it")
    }

    println(numbers)
}

Output:

List created: [10, 20, 30]
[10, 20, 30]

Explanation

The also() block prints the collection.

The original collection is returned and assigned to numbers.

When to Use also()

Use also() for:

  • Logging
  • Debugging
  • Additional operations
  • Inspecting intermediate values
  • Side effects that should not change the returned object

13. Kotlin also() for Logging

Let’s create a practical example.

data class User(
    val id: Int,
    val name: String
)

fun getUser(): User {

    return User(
        id = 101,
        name = "Alex"
    ).also {

        println("User loaded: $it")
    }
}

Usage

fun main() {

    val user = getUser()

    println(user.name)
}

Output:

User loaded: User(id=101, name=Alex)
Alex

Practical Android Example

val user = repository.getUser()
    .also { result ->
        Log.d(
            "UserRepository",
            "User result received: $result"
        )
    }

Here, repository.getUser() represents an existing repository method.

The also() block performs logging while preserving the returned result.

Security note: Avoid logging passwords, authentication tokens, personal information, or other sensitive data.


14. Kotlin this vs it Explained

Understanding this and it is the key to mastering scope functions.

Functions Using this

  • run()
  • with()
  • apply()

Functions Using it

  • let()
  • also()

Example Using this

val name = "Kotlin"

name.run {
    println(length)
}

The String object is the receiver, so its properties can be accessed directly.

Example Using it

val name = "Kotlin"

name.let {
    println(it.length)
}

The String is passed as the lambda argument.

Comparison

thisit
Receiver objectLambda argument
Direct member accessAccess through argument
Used by run, with, applyUsed by let, also
Convenient for configurationConvenient for transformations and side effects

Important

The implicit it parameter can be renamed.

For example:

name.let { value ->
    println(value.length)
}

Using descriptive names is often helpful in complex code.


15. Scope Function Return Values Explained

Scope functions return either the lambda result or the original object.

Functions Returning Lambda Result

  • let()
  • run()
  • with()

Functions Returning Original Object

  • apply()
  • also()

Example: let()

val result = "Kotlin".let {
    it.length
}

println(result)

Output:

6

Example: apply()

val result = StringBuilder().apply {
    append("Kotlin")
}

println(result.toString())

Output:

Kotlin

Example: also()

val result = "Kotlin".also {
    println("Processing $it")
}

println(result)

Output:

Processing Kotlin
Kotlin

Key Rule

Choose the scope function based on what you want to return and how you want to access the object.


16. Kotlin Scope Functions with Nullable Objects

Scope functions can be combined with Kotlin’s safe-call operator.

Using let()

val email: String? = "alex@example.com"

email?.let {
    println("Email: $it")
}

Using run()

val username: String? = "Alex"

val length = username?.run {
    length
}

println(length)

Output:

4

Using also()

val token: String? = "sample-token"

token?.also {
    println("Token is available")
}

Important

Scope functions do not automatically make nullable objects non-null.

The safe-call operator ?. is what skips execution when the receiver is null.

For production applications, avoid printing or logging actual authentication tokens.


17. Chaining Kotlin Scope Functions

Scope functions can be chained together.

Example

data class Product(
    var name: String = "",
    var price: Int = 0
)

fun main() {

    val product = Product()
        .apply {
            name = "Keyboard"
            price = 2500
        }
        .also {
            println("Created product: $it")
        }
        .run {
            "$name costs ₹$price"
        }

    println(product)
}

Output:

Created product: Product(name=Keyboard, price=2500)
Keyboard costs ₹2500

Explanation

First, apply() configures the object.

Next, also() logs the configured object.

Finally, run() transforms it into a String.

Best Practice

Avoid chaining too many scope functions.

Long chains can make it difficult to understand which object is currently being referenced and what each operation returns.

Prefer clear, readable code.


18. Practical Android Example: Processing an API Response

Suppose a repository returns user information.

We can use scope functions to process the response.

User Model

data class User(
    val id: Int,
    val name: String,
    val email: String
)

Example Repository Result

fun getUser(): User? {

    return User(
        id = 101,
        name = "Alex",
        email = "alex@example.com"
    )
}

Process the Result

fun main() {

    val user = getUser()

    val displayName = user?.let {

        println("User found: ${it.id}")

        it.name.uppercase()
    } ?: "Guest"

    println(displayName)
}

Output:

User found: 101
ALEX

Explanation

The let() block executes only when the user is not null.

The final expression returns the uppercase name.

If the user is null, the Elvis operator provides "Guest".

Practical Uses

This pattern is useful for:

  • Nullable repository results
  • Optional API fields
  • User profile information
  • Database lookups
  • UI model transformations

19. Practical Android Example: Configuring SharedPreferences

Let’s explore a traditional Android settings example.

val preferences = context.getSharedPreferences(
    "app_settings",
    Context.MODE_PRIVATE
)

preferences.edit().apply {

    putString("theme", "dark")

    putBoolean("notifications", true)

    apply()
}

Explanation

The outer Kotlin apply { ... } scope function provides access to the SharedPreferences editor.

The inner apply() call is the editor’s Android API method that asynchronously persists the changes.

These are two different functions with the same name.

Important

For new Android applications, Jetpack DataStore is generally a better choice for modern preference storage.

We’ll cover DataStore in a dedicated Android tutorial.


20. Jetpack Compose Mini-Project: User Profile Dashboard

Let’s build a simple Jetpack Compose screen that demonstrates Kotlin scope functions.

Our mini-project will include:

  • A user profile model
  • Profile initialization using apply()
  • Display name transformation using let()
  • Profile summary generation using run()
  • Logging using also()
  • A profile card built with Jetpack Compose

Step 1: Create the User Model

data class ProfileUser(
    var name: String = "",
    var email: String = "",
    var city: String = "",
    var age: Int = 0
)

Step 2: Create Sample Profile Data

fun createSampleUser(): ProfileUser {

    return ProfileUser().apply {

        name = "Alex"
        email = "alex@example.com"
        city = "Hyderabad"
        age = 28
    }
}

Explanation

The apply() function configures the ProfileUser object.

It then returns the configured object.

Step 3: Create the Profile Screen

@Composable
fun ScopeFunctionsProfileScreen() {

    val user = remember {
        createSampleUser()
    }

    val displayName = remember(user) {

        user.name.let {
            it.uppercase()
        }
    }

    val profileSummary = remember(user) {

        user.run {
            "$age years old • $city"
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {

        Text(
            text = "Kotlin Scope Functions",
            style = MaterialTheme.typography.headlineMedium
        )

        Card(
            modifier = Modifier.fillMaxWidth()
        ) {

            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {

                Text(
                    text = displayName,
                    style = MaterialTheme.typography.titleLarge
                )

                Text(
                    text = user.email,
                    style = MaterialTheme.typography.bodyMedium
                )

                Text(
                    text = profileSummary,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        Button(
            onClick = {

                user.also {
                    Log.d(
                        "ProfileDemo",
                        "Profile button clicked"
                    )
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {

            Text("View Profile")
        }
    }
}

Step 4: Required Imports

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

Expected UI

+--------------------------------+
|                                |
|     Kotlin Scope Functions     |
|                                |
| +----------------------------+ |
| |                            | |
| | ALEX                       | |
| |                            | |
| | alex@example.com           | |
| |                            | |
| | 28 years old • Hyderabad   | |
| |                            | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| |        View Profile        | |
| +----------------------------+ |
|                                |
+--------------------------------+

How It Works

apply() — Object Initialization

ProfileUser().apply {
    name = "Alex"
    age = 28
}

We use apply() to configure the user object.

let() — Data Transformation

user.name.let {
    it.uppercase()
}

We use let() to transform the username.

run() — Calculate a Result

user.run {
    "$age years old • $city"
}

We use run() to create a profile summary.

also() — Additional Action

user.also {
    Log.d("ProfileDemo", "Profile button clicked")
}

We use also() to perform an additional action while preserving the original object.

Production Note

This mini-project uses a simple sample object for demonstration.

In a production Android application, profile data would typically be managed through a ViewModel and exposed as observable UI state.

Also, avoid placing logging or other side effects directly inside composable rendering logic. User-triggered event callbacks are appropriate places for such operations.


21. Common Kotlin Scope Function Mistakes

Mistake 1: Using the Wrong Return Value

Consider:

val result = "Kotlin".also {
    it.uppercase()
}

The result is still:

Kotlin

Why?

Because also() returns the original object.

To return the transformed String, use let():

val result = "Kotlin".let {
    it.uppercase()
}

Output:

KOTLIN

Mistake 2: Confusing this and it

Remember:

  • let() uses it
  • also() uses it
  • run() uses this
  • with() uses this
  • apply() uses this

Mistake 3: Excessive Nesting

Avoid deeply nested scope functions.

user?.let {
    it.address?.let {
        it.city.let {
            println(it)
        }
    }
}

This becomes difficult to read because it refers to different objects.

Prefer descriptive parameter names or simpler expressions.

Mistake 4: Using Scope Functions Everywhere

Scope functions are optional.

Sometimes normal Kotlin statements are easier to understand.

Use them only when they improve readability.

Mistake 5: Forgetting Null Safety

This code:

nullableValue.let {
    // ...
}

does not skip the lambda when the value is null.

Use:

nullableValue?.let {
    // ...
}

when you want execution only for a non-null value.

Mistake 6: Performing Side Effects During Compose Rendering

Avoid using also() or other scope functions to trigger logging, network calls, or state mutations during ordinary composable rendering.

Compose functions may recompose multiple times.

Use appropriate event handlers and effect APIs such as LaunchedEffect when needed.


22. Kotlin Scope Functions Best Practices

Follow these recommendations:

  • Use let() for nullable values and transformations.
  • Use run() for calculations involving an object.
  • Use with() for multiple operations on an existing object.
  • Use apply() for object configuration.
  • Use also() for logging and additional actions.
  • Understand whether the function returns the object or lambda result.
  • Avoid deeply nested scope functions.
  • Use descriptive parameter names in complex lambdas.
  • Prefer straightforward Kotlin statements when clearer.
  • Avoid hiding expensive operations inside scope functions.
  • Keep Android lifecycle and Compose recomposition behavior in mind.
  • Write unit tests for important business logic.

These practices help create readable and maintainable Kotlin applications.


23. Kotlin Scope Functions Quick Reference

FunctionObject ReferenceReturnsExample
let()itLambda resultname?.let { it.uppercase() }
run()thisLambda resultuser.run { name }
with()thisLambda resultwith(user) { name }
apply()thisOriginal objectUser().apply { name = "Alex" }
also()itOriginal objectuser.also { println(it) }

Easy Way to Remember

let: Transform or handle nullable data.

run: Execute operations and return a result.

with: Work with an existing object.

apply: Configure and return the object.

also: Perform an additional action and return the object.


24. Practical Exercises

Try these exercises to improve your Kotlin scope function skills.

Exercise 1: let()

Create a nullable String.

Use let() to print its uppercase value only when it is not null.

Exercise 2: run()

Create a Rectangle data class.

Use run() to calculate its area.

Exercise 3: with()

Create a Student data class.

Use with() to display the student’s name, age, and course.

Exercise 4: apply()

Create a Product data class with mutable properties.

Use apply() to configure the product.

Exercise 5: also()

Create a list of numbers.

Use also() to print the list before processing it.

Exercise 6: Chaining

Create an object using apply().

Log it using also().

Transform it into a String using run().

Exercise 7: Null Safety

Create a nullable User object.

Use ?.let to display its name only when available.

Exercise 8: Jetpack Compose Mini-Project

Build a user profile card using:

  • Kotlin data classes
  • apply()
  • let()
  • run()
  • also()
  • remember
  • Material 3 Card
  • Button callbacks

25. Frequently Asked Questions

What are the five scope functions in Kotlin?

The five scope functions are let, run, with, apply, and also.

What is the difference between let and also?

Both use it to reference the object.

let() returns the lambda result, while also() returns the original object.

What is the difference between run and apply?

Both use this to reference the object.

run() returns the lambda result, while apply() returns the original object.

Which Kotlin scope function is best for null checks?

?.let { ... } is commonly used to execute code only when a nullable value is not null.

Which scope function is best for object initialization?

apply() is generally a good choice for configuring an object and returning it.

Are Kotlin scope functions mandatory?

No. They are convenience functions that can make Kotlin code more concise.

Use them when they improve readability.

Are scope functions used in Jetpack Compose?

Yes. They can be used for data transformations, object configuration, and supporting logic in Compose applications.

However, scope functions should not be used to introduce uncontrolled side effects during recomposition.


What We’ve Learned

In this tutorial, we learned:

  • Kotlin scope functions
  • let()
  • run()
  • with()
  • apply()
  • also()
  • this vs it
  • Lambda return values
  • Original object return values
  • Null-safe scope functions
  • Scope function chaining
  • Android object configuration
  • API response handling
  • Logging and debugging
  • Jetpack Compose integration
  • Common mistakes
  • Scope function best practices

Kotlin scope functions are powerful tools for writing concise and expressive code.

Understanding when to use each function will help you improve code readability and maintainability in Android applications.

The most important rule is simple:

Choose the scope function based on how you want to access the object and what you want the function to return.


What’s Next?

In our next tutorial, we’ll explore:

Kotlin Generics Explained: Type Parameters, Constraints & Variance

You’ll learn:

  • What generics are
  • Generic classes
  • Generic functions
  • Type parameters
  • Generic constraints
  • in and out variance
  • Covariance and contravariance
  • Star projections
  • Practical Android examples
  • Generic repository patterns
  • Jetpack Compose use cases

Happy Coding!

Continue learning modern Android development with Moiks Developer Blog.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment