Ukraine needs your help!

Series: Kotlin Scope Functions

Scope function - let


Most often using the scope function “let {}”, allows you to write readable and intuitive code, but if you are doing that correctly.

What is Scope Function?

Scope functions in Kotlin are list of functions that allow you to access the context object as a lambda argument.

Scope Function: let

Yes, a lot of developers start from this function, I even could say that you have used the following code:

val myVar: String? = getSomething()
myVar?.let {
  // do something

It is usual safe unwrap null and it’s ok. When ?. means that function will be performed only if myVar not null.

First we are calling some function and expecting that the result could be null, usually in java we was doing something like:

String myVar = getSomething();
if (myVar) // do something

But in Kotlin it looks more readable, take a look at the code below:

val order: Order? = getOrder(orderId)
val archivedOrder = order?.let {
	if(it.createdAt > 10) it.copy(status = "ARCHIVED")


This code could be optimised:

val order: Order = getOrder(orderId)?.let {
	if(it.createdAt > 10) saveOrder(it.copy(status = "ARCHIVED"))

Pay attention, now order is not nullable, and you can use it without any null checks.

Let’s review one more useful use of let {}, imagine we have a flow of managing orders and we have to check if an order exists and then apply some special offer for this order, otherwise initialize default order.

Using Java it looks like:

Order order = getOrder(orderId);
if (order != null) {
  order = applyOfferForOrder(order);
} else {
  order = createDefaultOrder();
// do something with order

Let’s review the same logic using Kotlin and let {}:

val order = getOrder(orderId)?.let { 
} ?: createDefaultOrder()

First, we are trying to get order, if order exists then we are applying offer, otherwise createDefaultOrder(). Using ?: means if left side before this condition is null, then will be performed right side.


Alex BarchukBlog about programming 🚀 © 2023