← Back to Kotlin Course | Chapter 10: Extension Functions & Properties | Lesson 3 of 6

Scope Functions को गहराई से समझना

Scope functions tools का एक छोटा family हैं जो सभी किसी value के करीब code का एक block चलाते हैं, लेकिन हर एक थोड़ा अलग result वापस देता है।
Syntax
kotlin
val r1 = receiver.let { it -> result }      // returns the block result
val r2 = receiver.run { this -> result }
val r3 = receiver.also { it -> }             // returns receiver
val r4 = receiver.apply { this -> }          // returns receiver
val r5 = with(receiver) { this -> result }

Comparing Return Values

apply और also हमेशा original receiver object return करते हैं, जबकि let, run, और with अपनी आखिरी expression के रूप में lambda block जो भी produce करे वह return करते हैं।

उदाहरण: Comparing Return Values

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `listApply`, set to `mutableListOf(1, 2).apply { add(3) }`
    val listApply = mutableListOf(1, 2).apply { add(3) }
    // Declare a read-only variable `sizeRun`, set to `mutableListOf(1, 2).run { add(3); size }`
    val sizeRun = mutableListOf(1, 2).run { add(3); size }
    // Print "apply result: $listApply" to the console, with a trailing newline
    println("apply result: $listApply")
    // Print "run result: $sizeRun" to the console, with a trailing newline
    println("run result: $sizeRun")
}

Comparing this vs it

apply, run, और with receiver को this के रूप में उपलब्ध कराते हैं (अक्सर छोड़ दिया जाता है), जबकि let और also इसे it, एक explicit parameter name, के रूप में उपलब्ध कराते हैं।

उदाहरण: Comparing this vs it

markup
data class Box(var content: String)

fun main() {
    val box = Box("empty")
    box.apply { content = "full" } // this.content
    box.also { println("Box now has: ${it.content}") } // it.content
}

Choosing let for Transformation

let आदर्श है जब आप किसी value को किसी और चीज़ में transform करना चाहें और वह नया result वापस पाना चाहें, खासकर किसी nullable value पर safe call के साथ combine करते समय।

उदाहरण: Choosing let for Transformation

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `name` (a `String?`), set to `"kotlin"`
    val name: String? = "kotlin"
    // Declare a read-only variable `length`, set to `name?.let { it.length }`
    val length = name?.let { it.length }
    // Print "Length: $length" to the console, with a trailing newline
    println("Length: $length")
}

Choosing apply for Configuration

apply आदर्श है जब किसी object की properties configure करते समय आप आखिर में पूरी तरह configured object खुद वापस चाहें, बिना एक अलग computed result की ज़रूरत के।

उदाहरण: Choosing apply for Configuration

markup
// Define a class `Settings`
class Settings {
    // Declare a mutable variable `darkMode`, initialized to `false`
    var darkMode = false
    // Declare a mutable variable `fontSize`, initialized to `12`
    var fontSize = 12
}

// Entry point: execution of the program starts here
fun main() {
    // Call `Settings().apply` with a trailing lambda, storing the result in `settings`
    val settings = Settings().apply {
        darkMode = true
        fontSize = 16
    }
    // Print "Dark mode: ${settings.darkMode}, Font size: ${settings.fontSize}" to the console, with a trailing newline
    println("Dark mode: ${settings.darkMode}, Font size: ${settings.fontSize}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. काम के लिए गलत scope function चुनना, जैसे apply उपयोग करना जब मकसद block की अपनी computed value थी (जिसके लिए run या let चाहिए)।
  2. scope functions को गहराई से nest करना, यह बताना मुश्किल बनाते हुए कि कौन सा this/it किस block का है।
  3. सिर्फ style के लिए scope function उपयोग करना जब एक साधारण statement ज़्यादा साफ़ और उतना ही छोटा होता।
चैप्टर सारांश
  • let, run, with, apply, और also सब एक receiver के खिलाफ एक block execute करते हैं लेकिन इसमें अलग हैं कि वे क्या return करते हैं और क्या receiver this है या it।
  • apply और also original receiver return करते हैं; let, run, और with block का result return करते हैं।
  • apply, run, और with receiver को this के रूप में उजागर करते हैं; let और also इसे it के रूप में उजागर करते हैं।
  • सही scope function चुनना इस पर निर्भर करता है कि आपको क्या वापस चाहिए: original object, या एक transformed result।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.