Using the let function

With the help of Lambda and extension functions, Kotlin is providing yet another powerful feature in the form of let functions. The let() function helps you execute a series of steps on the calling object. This is highly useful when you want to perform some code where the calling object is used multiple times and you want to avoid a null check every time.

In the following code block, the forEach loop will only get executed if onlineUsersList is not null. We can refer to the calling object inside the let function using it:

    fun showOnlineUsers(data: Json) {      val onlineUsersList = document.getElementById("onlineUsersList")      onlineUsersList?.let {        val usersList = data["usersList"] as? Array<String>        usersList?.forEachIndexed ...

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.