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.
The figure shows how the safe-call operator limits lambda execution to non-null expressions, especially after a nullable expression chain. section 7.8
