🐦 Kotlin Beginner

What does the let scope function do in Kotlin?

Answer

The let scope function executes a block of code with the object as its argument (accessed as it inside the block) and returns the result of the block. It is most commonly used for null-safe operations: name?.let { println(it.uppercase()) } — the block only runs if name is not null. It is also useful for chaining transformations or when you want to confine a variable's scope to a specific block. Unlike apply and also, let returns the block's result, not the original object.