Kotlin - Scope Functions

Overview

Scope functions in Kotlin provide a way to execute code blocks within the context of an object. The five scope functions (let, run, with, apply, also) allow for more concise and readable code by providing different ways to access and manipulate objects within a specific scope.

🎯 Learning Objectives:
  • Understand the five scope functions and their differences
  • Learn when to use let, run, with, apply, and also
  • Master context object access (this vs it)
  • Apply scope functions for null safety and object initialization
  • Understand return values and chaining patterns

let Function

The let function is primarily used for null safety checks and transformations.

// Basic transformation
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.let { list ->
    list.map { it * 2 }
}
println("Doubled: $doubled")  // Doubled: [2, 4, 6, 8, 10]

// Null safety with let
fun processString(str: String?): String {
    return str?.let { nonNullStr ->
        "Processed: ${nonNullStr.uppercase()}"
    } ?: "String was null"
}

fun main() {
    println(processString("hello"))  // Processed: HELLO
    println(processString(null))     // String was null
}

Practice Exercises

  1. Use let for safe null operations
  2. Use apply for object initialization
  3. Use also for logging and side effects