← Back to Kotlin Course | Chapter 4: Functions | Lesson 5 of 7

Local Functions क्या हैं

एक local function एक helper recipe है जिसे आप किसी दूसरे function के अंदर सीधे define करते हैं, सिर्फ उस function के अपने उपयोग के लिए।
Syntax
kotlin
fun outerFunction(param: Type) {
    fun localFunction(x: Type): ReturnType {
        return value   // can use param from outer
    }
    localFunction(value)
}

Declaring a Local Function

किसी दूसरे function के body के अंदर defined function एक local function है, जो सिर्फ उस enclosing function के अंदर उपयोग करने योग्य है, छोटे helpers को उन्हें जहां ज़रूरत है वहां कसकर scope में रखते हुए।

उदाहरण: Declaring a Local Function

markup
// Define the function `printReport` taking `total`
fun printReport(total: Int) {
    // Define the function `formatCurrency` taking `amount` and returning a String
    fun formatCurrency(amount: Int): String = "$$amount.00"

    // Print "Total: ${formatCurrency(total)}" to the console, with a trailing newline
    println("Total: ${formatCurrency(total)}")
}

// Entry point: execution of the program starts here
fun main() {
    printReport(150)
}

Accessing Enclosing Variables

एक local function उस function के variables को सीधे पढ़ सकता है जिसके अंदर यह nested है, उन्हें parameters के रूप में पास किए बिना।

उदाहरण: Accessing Enclosing Variables

markup
// Define the function `calculateDiscountedTotal` taking `prices`, `discountPercent`
fun calculateDiscountedTotal(prices: List<Int>, discountPercent: Int) {
    // Define the function `applyDiscount` taking `price` and returning an Int
    fun applyDiscount(price: Int): Int = price - (price * discountPercent / 100)

    // Declare a read-only variable `total`, set to `prices.sumBy { applyDiscount(it) }`
    val total = prices.sumBy { applyDiscount(it) }
    // Print "Discounted total: $total" to the console, with a trailing newline
    println("Discounted total: $total")
}

// Entry point: execution of the program starts here
fun main() {
    calculateDiscountedTotal(listOf(100, 200, 300), 10)
}

Breaking Up Long Functions

दोहराए गए या logically अलग steps को local functions में निकालना outer function के body को overall flow पर केंद्रित रखता है, जबकि details named, isolation-में-testable टुकड़ों में रहती हैं।

उदाहरण: Breaking Up Long Functions

markup
// Define the function `processOrder` taking `itemCount`, `pricePerItem`
fun processOrder(itemCount: Int, pricePerItem: Int) {
    fun subtotal() = itemCount * pricePerItem
    fun tax(amount: Int) = amount / 10

    // Declare a read-only variable `sub`, set to `subtotal()`
    val sub = subtotal()
    // Print "Subtotal: $sub, Tax: ${tax(sub)}" to the console, with a trailing newline
    println("Subtotal: $sub, Tax: ${tax(sub)}")
}

// Entry point: execution of the program starts here
fun main() {
    processOrder(3, 50)
}

When to Avoid Local Functions

अगर किसी helper को कई असंबंधित functions में reuse होना है, तो इसे local के बजाय एक regular top-level (या member) function होना चाहिए, क्योंकि local functions को उनके enclosing function के बाहर से call नहीं किया जा सकता।

उदाहरण: When to Avoid Local Functions

markup
fun square(x: Int) = x * x

// Define the function `sumOfSquares` taking `a`, `b` and returning an Int
fun sumOfSquares(a: Int, b: Int): Int {
    // Return `square(a) + square(b)` from this function
    return square(a) + square(b)
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Sum of squares: ${sumOfSquares(3, 4)}" to the console, with a trailing newline
    println("Sum of squares: ${sumOfSquares(3, 4)}")
}
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. किसी helper को top-level function बनाना जब इसकी ज़रूरत सिर्फ एक दूसरे function के अंदर हो, file के namespace को गड़बड़ करते हुए।
  2. यह भूल जाना कि एक local function सीधे अपने enclosing function के variables को access कर सकता है, जिससे अनावश्यक parameters पास किए जाते हैं।
  3. local functions को बहुत गहराई से nest करना, readability को मदद करने के बजाय चोट पहुंचाते हुए।
चैप्टर सारांश
  • एक local function किसी दूसरे function के body के अंदर declare होता है और सिर्फ वहीं दिखाई देता है।
  • Local functions अपने enclosing function के scope के variables को सीधे पढ़ (और अगर var हो तो modify) सकते हैं।
  • वे outer file scope को गंदा किए बिना एक लंबे function को छोटे named टुकड़ों में तोड़ने में मदद करते हैं।
  • बहुत गहराई से nested local functions का ज़्यादा उपयोग readability को उतना ही नुकसान पहुंचा सकता है जितना एक विशाल function।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.