← Back to Kotlin Course | Chapter 6: Classes & Objects | Lesson 4 of 7

init Block क्या है

एक init block setup code का एक टुकड़ा है जो एक नए object के बनते ही अपने आप चलता है, किसी और के इसे उपयोग करने से पहले।
Syntax
kotlin
class ClassName(val property: Type) {
    init {
        require(condition) { "message" }   // runs when created
    }
}

Running Setup Code with init

एक init block में वह code होता है जो किसी instance के बनते ही तुरंत चलता है, validation या setup logic के लिए उपयोगी जो एक साधारण property assignment से आगे जाती है।

उदाहरण: Running Setup Code with init

markup
// Define a class `Person`
class Person(val name: String, val age: Int) {
    init {
        // Print "Creating person: $name, age $age" to the console, with a trailing newline
        println("Creating person: $name, age $age")
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `person`, set to `Person("Ana", 30)`
    val person = Person("Ana", 30)
    // Print "Created: ${person.name}" to the console, with a trailing newline
    println("Created: ${person.name}")
}

Validating Constructor Arguments

init का एक आम उपयोग primary constructor को पास की गई values को validate करना है, कुछ invalid होने पर तुरंत एक exception फेंकते हुए।

उदाहरण: Validating Constructor Arguments

markup
// Define a class `Age`
class Age(val value: Int) {
    init {
        require(value >= 0) { "Age cannot be negative" }
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `age`, set to `Age(25)`
    val age = Age(25)
    // Print "Valid age: ${age.value}" to the console, with a trailing newline
    println("Valid age: ${age.value}")
}

Multiple init Blocks and Property Order

एक class में एक से ज़्यादा init block हो सकते हैं, और Kotlin उन्हें, property initializers के साथ मिलाकर, class body में दिखने के बिल्कुल ऊपर-से-नीचे order में चलाता है।

उदाहरण: Multiple init Blocks and Property Order

markup
// Define a class `Steps`
class Steps {
    // Declare a read-only variable `first`, set to `println("Step 1: property initialized").let { "done" }`
    val first = println("Step 1: property initialized").let { "done" }
    init {
        // Print "Step 2: first init block" to the console, with a trailing newline
        println("Step 2: first init block")
    }
    // Declare a read-only variable `second`, set to `println("Step 3: second property initialized").let { "done" }`
    val second = println("Step 3: second property initialized").let { "done" }
    init {
        // Print "Step 4: second init block" to the console, with a trailing newline
        println("Step 4: second init block")
    }
}

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

init Blocks with Secondary Constructors

चूंकि हर secondary constructor को primary constructor को delegate करना चाहिए, init blocks हमेशा किसी secondary constructor की अपनी body execute होने से पहले चलते हैं।

उदाहरण: init Blocks with Secondary Constructors

markup
// Define a class `Logger`
class Logger(val prefix: String) {
    init {
        // Print "[$prefix] Logger initialized" to the console, with a trailing newline
        println("[$prefix] Logger initialized")
    }

    constructor() : this("DEFAULT") {
        // Print "Secondary constructor body running" to the console, with a trailing newline
        println("Secondary constructor body running")
    }
}

// Entry point: execution of the program starts here
fun main() {
    Logger()
}
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. यह भूल जाना कि कई init blocks और property initializers class body में लिखे गए बिल्कुल उसी order में चलते हैं, किसी अलग fixed order में नहीं।
  2. init में ऐसा logic डालना जो किसी secondary constructor के parameter पर निर्भर हो, यह भूलते हुए कि init blocks secondary constructor bodies से पहले चलते हैं (लेकिन primary constructor की अपनी delegation के बाद)।
  3. हर secondary constructor में validation logic दोहराना बजाय shared checks को एक बार init block में रखने के।
चैप्टर सारांश
  • init blocks instance creation के हिस्से के रूप में चलते हैं, class body में property initializers के साथ दिखाई देने वाले order में।
  • किसी class में कई init blocks हो सकते हैं, और वे property initialization के साथ मिलकर ऊपर-से-नीचे execute होते हैं।
  • init blocks primary constructor parameters को सीधे access कर सकते हैं, क्योंकि वे primary construction के हिस्से के रूप में चलते हैं।
  • हर instance के लिए common validation logic अक्सर हर constructor में दोहराने के बजाय एक init block में रखा जाता है।
🔒

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.