SyntaxStudy
Sign Up
Kotlin Inline Functions and Scope Functions
Kotlin Beginner 1 min read

Inline Functions and Scope Functions

The inline modifier on a higher-order function instructs the compiler to copy the function body — and any lambda arguments — directly into the call site. This eliminates the overhead of object creation for lambdas and enables non-local returns from lambdas, which is otherwise forbidden. Kotlin's standard library provides five scope functions — let, run, with, apply, and also — that execute a block of code in the context of an object. They differ in how they refer to the context object (this vs it) and what they return (the object itself or the lambda result). These scope functions are not strictly necessary but make code more concise and expressive: apply is ideal for object configuration, let for null-safe transformations, also for side effects, run for computing a result from an object, and with for grouping multiple calls on the same object.
Example
data class Config(
    var host: String = "localhost",
    var port: Int = 8080,
    var debug: Boolean = false
)

fun main() {
    // apply — configures an object, returns the object
    val config = Config().apply {
        host  = "example.com"
        port  = 443
        debug = true
    }
    println(config)

    // let — transforms a nullable value, returns lambda result
    val name: String? = "  Kotlin  "
    val length = name?.let {
        val trimmed = it.trim()
        println("Trimmed: '$trimmed'")
        trimmed.length
    }
    println("Length: $length")

    // run — execute block, return result; also used on an object
    val summary = config.run {
        "Connecting to $host:$port (debug=$debug)"
    }
    println(summary)

    // also — side effect, returns the original object
    val numbers = mutableListOf(3, 1, 4, 1, 5)
        .also { println("Before sort: $it") }
        .also { it.sort() }
        .also { println("After sort: $it") }

    // with — group calls (not an extension, receiver = this)
    val message = with(StringBuilder()) {
        append("Hello")
        append(", ")
        append("Kotlin!")
        toString()
    }
    println(message)
}