liveBook · Manning

Let

As explained in Kotlin in Action, 2E

let is a Kotlin standard-library function that executes a lambda with the receiver supplied as an argument and returns the lambda's result.

let is a Kotlin scope function that passes its receiver to a lambda. With a safe call, it runs the lambda only when a nullable value is non-null, exposing that value as a non-nullable lambda argument. section 7.13 section 7.8

Call a function that requires a non-null value

fun sendEmailTo(email: String) { println("Sending email to $email") } fun main() { var email: String? = "yole@example.com" email?.let { sendEmailTo(it) } email = null email?.let { sendEmailTo(it) } } The first call sends the email. The second call does nothing because the safe call prevents the let lambda from running. The short name it refers to the non-null String inside the lambda. section 7.8

Use let when a nullable result needs a concise, scoped operation:

  • Replace an explicit null check when passing a nullable value to a function requiring a non-nullable parameter. section 7.8
  • Apply an operation directly to a longer nullable expression without introducing an intermediate variable. section 7.8
  • Use nested let calls for multiple nullable values only cautiously; a regular if expression is usually easier to follow. section 7.8
Figure 7.6 Together with the safe-call operator, let allows you to specify a lambda that is executed only if your expression isn’t null. This is particularly useful when you are working with the result of a chain of expressions that happens to be nullable.
CH07_F06_Isakova

The figure shows how the safe-call operator limits lambda execution to non-null expressions, especially after a nullable expression chain. section 7.8

How Kotlin in Action, 2E covers it

How deep it goes
Explains receiver-to-lambda binding, safe-call execution, longer expressions, and nested-let tradeoffs, but stops short of implementation internals.
Examples
Demonstrates email sending, explicit null checks, nullable expression chains, and nested let calls.
What it assumes
Assumes lambdas and nullable types while establishing safe calls and non-nullable lambda arguments through examples.
What you can do after
Apply it in Kotlin to perform conditional operations on nullable values without duplicating explicit null checks.
How it connects
Connects nullable types, safe calls, lambdas, non-nullable types, and other Kotlin scope functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.