← Back to Scala Course | Chapter 7: OOP Basics | Lesson 5 of 7

Companion Objects क्या हैं

एक companion object एक साथी है जो किसी class का नाम share करता है, और उन चीज़ों को रखता है जो पूरी class से जुड़ी हैं, न कि किसी एक copy से। यह classrooms के पास किसी school के office जैसा है।

In this page:

  1. Companion Objects
Syntax
scala
class ClassName {
  // instance members
}

object ClassName {
  def apply(param: Type) = new ClassName
}

Companion Objects

एक companion object एक object है जो उसी file में किसी class के साथ बिल्कुल वही नाम share करता है, जिससे उन्हें एक-दूसरे के private members तक विशेष आपसी access मिलती है।

Companion objects आमतौर पर factory methods (अक्सर apply नाम से, जो आपको new ClassName(args) के बजाय ClassName(args) लिखने देता है) और static जैसे utility members रखते हैं। यह Java के static keyword का Scala का संरचित विकल्प है।

Note: companion object में apply define करना आपको new keyword के बिना instances बनाने देता है, जैसे Point(1, 2)।

उदाहरण: Companion Objects

markup
class Point(val x: Int, val y: Int) {
  override def toString: String = s"Point($x, $y)"
}

object Point {
  def apply(x: Int, y: Int): Point = new Point(x, y)
  def origin: Point = new Point(0, 0)
}

object Main extends App {
  val p1 = Point(3, 4) // uses companion object's apply, no 'new'
  val p0 = Point.origin

  println(p1)
  println(p0)
}
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 को class से अलग file में रखना, जबकि private members share करने के लिए इसे एक ही file में होना चाहिए।
  2. new Point(1, 2) call करना और apply method के उपयोग होने की उम्मीद करना, जबकि Point(1, 2) ही apply call करता है।
  3. object के नाम के लिए अलग spelling या case का उपयोग करना, जिससे यह companion के बजाय एक अलग object बन जाता है।
🔒

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.