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

Companion Objects क्या हैं

एक companion object किसी class से जुड़ा एक खास helper है, ताकि आप उस class का instance बनाए बिना इसे call कर सकें।
Syntax
kotlin
class ClassName {
    companion object {
        const val CONSTANT = value
        fun factory(): ClassName = ClassName()
    }
}

ClassName.factory()

Declaring a Companion Object

किसी class के अंदर एक companion object block ऐसे members रखता है जो पहले एक instance बनाए बिना, class name के ज़रिए सीधे accessible हैं।

उदाहरण: Declaring a Companion Object

markup
// Define a class `Circle`
class Circle(val radius: Double) {
    companion object {
        const val PI_APPROX = 3.14159
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Pi approximation: ${Circle.PI_APPROX}" to the console, with a trailing newline
    println("Pi approximation: ${Circle.PI_APPROX}")
}

Factory Functions in a Companion Object

एक आम pattern है किसी companion object के अंदर एक factory function define करना जो instances बनाता और return करता है, अक्सर construction की details छुपाने या customize करने के लिए उपयोग होता है।

उदाहरण: Factory Functions in a Companion Object

markup
// Define a class `User`
class User private constructor(val name: String) {
    companion object {
        // Define the function `createGuest` with no parameters and returning a `User`
        fun createGuest(): User = User("Guest")
    }
}

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

Constants with const val

Companion objects const val का उपयोग करके compile-time constants define करने की एक स्वाभाविक जगह हैं, जो सीधे compile time पर resolve होते हैं और class name के ज़रिए access किए जाते हैं।

उदाहरण: Constants with const val

markup
// Define a class `Circle`
class Circle(val radius: Double) {
    companion object {
        const val UNIT = "cm"
    }

    fun describe() = "Radius: $radius $UNIT"
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `circle`, set to `Circle(5.0)`
    val circle = Circle(5.0)
    // Print `circle.describe()` to the console, with a trailing newline
    println(circle.describe())
}

Naming a Companion Object

किसी companion object को optionally एक नाम दिया जा सकता है, जैसे companion object Factory, जिसे फिर अतिरिक्त स्पष्टता के लिए default class-name access के साथ-साथ उपयोग किया जा सकता है।

उदाहरण: Naming a Companion Object

markup
// Define a class `Widget`
class Widget private constructor(val id: Int) {
    companion object Factory {
        // Define the function `create` taking `id` and returning a `Widget`
        fun create(id: Int): Widget = Widget(id)
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `widget`, set to `Widget.Factory.create(7)`
    val widget = Widget.Factory.create(7)
    // Print "Widget id: ${widget.id}" to the console, with a trailing newline
    println("Widget id: ${widget.id}")
}
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. किसी companion object के members को Java में static members के साथ confuse करना; Kotlin में कोई static keyword नहीं है, companion objects इसके सबसे करीबी equivalent हैं।
  2. यह भूल जाना कि एक companion object एक असली singleton object है, और यह interfaces implement कर सकता है या साधारण factory functions से आगे अपनी properties रख सकता है।
  3. प्रति class एक से ज़्यादा companion object declare करने की कोशिश करना; प्रति class सिर्फ एक companion object की अनुमति है।
चैप्टर सारांश
  • किसी class के अंदर companion object { ... } ऐसे members declare करता है जो खुद class से belong करते हैं, individual instances से नहीं।
  • Companion object members ClassName.member के ज़रिए access किए जाते हैं, दूसरी languages में static members जैसा।
  • एक companion object को नाम दिया जा सकता है, लेकिन unnamed होने पर यह default रूप से Companion नाम लेता है।
  • Companion objects आमतौर पर class से संबंधित factory functions, constants, या shared configuration रखते हैं।
🔒

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.