Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. let

let

A scope function that passes an object into a lambda's scope and returns the result of the lambda. Commonly used in combination with null-safe operations.

Syntax

// Refers to the object as it inside the lambda. The return value is the last expression.
object.let { it ->
    // Operations using it
    returnValue
}

// Executes the block only when the value is non-null (used with safe call operator).
nullableObject?.let { it ->
    // This block runs only when the value is non-null.
}

Overview

ItemDescription
Context object referenceReferenced as the lambda argument it.
Return valueReturns the result of the lambda (the value of the last expression).
Common use casesNull checks, transformation operations, and eliminating temporary variables.

Sample Code

fun main() {
    // Basic usage: transform a value and capture the result.
    val length = "Hello, Kotlin".let { it.length }
    println(length) // 13

    // The block is skipped when the value is null.
    val name: String? = "Taro"
    val greeting = name?.let { "Hello, ${it}!" }
    println(greeting) // Hello, Taro!

    // When the value is null, let is not called and null is returned.
    val nullName: String? = null
    val result = nullName?.let { "Hello, ${it}!" }
    println(result) // null

    // Chain multiple transformations in sequence.
    val score = "  85  "
        .let { it.trim() }
        .let { it.toInt() }
        .let { it * 2 }
    println(score) // 170

    // Complete a series of operations in a block without a temporary variable.
    val message = listOf("Kotlin", "Java", "Swift")
        .let { languages ->
            // You can give the argument an explicit name instead of using it.
            languages.joinToString(separator = " / ")
        }
    println(message) // Kotlin / Java / Swift
}

Overview (Details)

let passes the context object as a lambda argument and returns the last expression of the lambda as its result. Inside the lambda, the object is referenced as it, but you can also give the argument an explicit name.

The most common use case is null-safe processing with ?.let { }. Nesting ?.let { } reduces readability — avoid more than two levels of nesting and consider alternatives such as chaining or splitting into separate functions. For guidance on choosing between scope functions, see also run / with, apply, and also.

If you find any errors or copyright issues, please .