0
0
Kotlinprogramming~5 mins

Run function behavior and use cases in Kotlin

Choose your learning style9 modes available
Introduction

The run function helps you execute a block of code and return its result in a simple way. It makes your code cleaner and easier to read.

When you want to execute multiple statements and return the last expression as a result.
When you want to limit the scope of variables to a small block of code.
When you want to perform operations on an object and return a value without creating a separate function.
When you want to initialize an object and immediately use it in a concise way.
When you want to avoid repeating the object name multiple times in a block.
Syntax
Kotlin
val result = run {
    // code block
    // last expression is returned
}

The run function takes a lambda block and returns the value of the last expression inside it.

You can use run without an object or as an extension function on an object.

Examples
This runs a block that adds two numbers and returns the sum.
Kotlin
val result = run {
    val x = 5
    val y = 10
    x + y
}
This runs a block on the string "hello", prints it, and returns its length.
Kotlin
val length = "hello".run {
    println(this)
    this.length
}
This creates a greeting message inside the block and returns it.
Kotlin
val message = run {
    val name = "Anna"
    "Hello, $name!"
}
Sample Program

This program shows two uses of run. First, it sums two numbers inside a block and prints the result. Second, it runs a block on a string, prints it, and returns its length.

Kotlin
fun main() {
    val sum = run {
        val a = 3
        val b = 7
        a + b
    }
    println("Sum is: $sum")

    val textLength = "Kotlin".run {
        println("Word: $this")
        this.length
    }
    println("Length is: $textLength")
}
OutputSuccess
Important Notes

The run function is useful to keep variables local and avoid polluting the outer scope.

Inside run, this refers to the object if used as an extension function.

Use run to make your code more readable and concise when you need a temporary scope.

Summary

run executes a block and returns the last expression.

It helps keep code clean by limiting variable scope.

You can use it with or without an object to simplify code.