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

Object Declarations क्या हैं

एक object declaration किसी चीज़ का अपने आप बिल्कुल एक single instance बनाता है, ताकि आपको इसे कभी खुद बनाने की ज़रूरत न पड़े।
Syntax
kotlin
object ObjectName {
    val property: Type = value
    fun method() { }
}

ObjectName.property
ObjectName.method()

Declaring a Singleton

object Name { ... } एक साथ class और इसका single instance दोनों define करता है; कोई अलग constructor call नहीं होता -- आप इसे उपयोग करने के लिए बस सीधे Name को refer करते हैं।

उदाहरण: Declaring a Singleton

markup
// Define the singleton object `AppConfig`
object AppConfig {
    // Declare a read-only variable `appName`, set to `"MyApp"`
    val appName = "MyApp"
    // Declare a mutable variable `debugMode`, initialized to `false`
    var debugMode = false
}

// Entry point: execution of the program starts here
fun main() {
    // Print `AppConfig.appName` to the console, with a trailing newline
    println(AppConfig.appName)
    AppConfig.debugMode = true
    // Print "Debug: ${AppConfig.debugMode}" to the console, with a trailing newline
    println("Debug: ${AppConfig.debugMode}")
}

Object Declarations for Utility Functions

Objects stateless utility functions के लिए एक स्वाभाविक जगह हैं जो logically साथ belong करते हैं लेकिन हर call के लिए एक instance की ज़रूरत नहीं।

उदाहरण: Object Declarations for Utility Functions

markup
// Define the singleton object `MathUtils`
object MathUtils {
    fun square(x: Int) = x * x
    fun cube(x: Int) = x * x * x
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Square of 5: ${MathUtils.square(5)}" to the console, with a trailing newline
    println("Square of 5: ${MathUtils.square(5)}")
    // Print "Cube of 3: ${MathUtils.cube(3)}" to the console, with a trailing newline
    println("Cube of 3: ${MathUtils.cube(3)}")
}

Lazy Initialization

किसी object का instance पहली बार access होने पर बनता है, ज़रूरी नहीं कि program शुरू होने पर, जिसे इसके अपने init block से print करके देखा जा सकता है।

उदाहरण: Lazy Initialization

markup
// Define the singleton object `Session`
object Session {
    init {
        // Print "Session object created" to the console, with a trailing newline
        println("Session object created")
    }
    // Declare a read-only variable `id`, set to `"abc123"`
    val id = "abc123"
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Before accessing Session" to the console, with a trailing newline
    println("Before accessing Session")
    // Print "Session id: ${Session.id}" to the console, with a trailing newline
    println("Session id: ${Session.id}")
}

Object Expressions for One-Off Instances

एक anonymous object : Type { ... } एक interface implement करता या class extend करता single-use instance बनाता है, एक पूरी named class declare किए बिना एक तेज़, throwaway implementation के लिए उपयोगी।

उदाहरण: Object Expressions for One-Off Instances

markup
// Define an interface `ClickListener` describing required behavior
interface ClickListener {
    // Define the function `onClick` with no parameters
    fun onClick()
}

// Entry point: execution of the program starts here
fun main() {
    // Call `object : ClickListener` with a trailing lambda, storing the result in `listener`
    val listener = object : ClickListener {
        override fun onClick() {
            // Print "Clicked!" to the console, with a trailing newline
            println("Clicked!")
        }
    }
    listener.onClick()
}
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. किसी object declaration को constructor arguments पास करने की कोशिश करना; object से declared singletons constructor parameters नहीं ले सकते।
  2. यह भूल जाना कि एक object पहली access पर lazily initialize होता है, program startup पर नहीं, जो इसके init block में side effects के लिए मायने रख सकता है।
  3. object declarations (named singletons) को one-off implementations के लिए उपयोग होने वाले anonymous object expressions के साथ confuse करना।
चैप्टर सारांश
  • object Name { ... } एक singleton declare करता है -- बिल्कुल एक instance जो पहली access पर lazily बनता है।
  • Singletons constructor parameters नहीं ले सकते क्योंकि इन्हें बनाने के लिए कोई explicit call नहीं होता।
  • एक anonymous object : SomeType { ... } (एक object expression) एक interface implement करता या class extend करता एक one-off instance बनाता है, अक्सर वहां उपयोग होता है जहां Java anonymous class उपयोग होती।
  • Object declarations आमतौर पर utility functions, constants, और shared state के लिए उपयोग होते हैं जो बिल्कुल एक बार मौजूद होनी चाहिए।
🔒

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.