Companion Objects क्या हैं
एक companion object एक साथी है जो किसी class का नाम share करता है, और उन चीज़ों को रखता है जो पूरी class से जुड़ी हैं, न कि किसी एक copy से। यह classrooms के पास किसी school के office जैसा है।
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- companion object को class से अलग file में रखना, जबकि private members share करने के लिए इसे एक ही file में होना चाहिए।
new Point(1, 2)call करना औरapplymethod के उपयोग होने की उम्मीद करना, जबकिPoint(1, 2)हीapplycall करता है।- object के नाम के लिए अलग spelling या case का उपयोग करना, जिससे यह companion के बजाय एक अलग object बन जाता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: