Companion Objects
A companion object is a partner sharing a class's name, holding the things that belong to the whole class rather than one copy. It is like a school's office next to the classrooms.
In this page:
Syntax
class ClassName {
// instance members
}
object ClassName {
def apply(param: Type) = new ClassName
}
Companion Objects
A companion object is an object sharing the exact same name as a class in the same file, giving them special mutual access to each other's private members.
Companion objects commonly hold factory methods (often named apply, which lets you write ClassName(args) instead of new ClassName(args)) and static-like utility members. This is Scala's structured alternative to Java's static keyword.
Note:
Defining
apply in a companion object lets you construct instances without the new keyword, like Point(1, 2).Example: 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. #}
Common Mistakes
- Putting the companion object in a different file from the class, when it must be in the same file to share private members.
- Calling
new Point(1, 2)and expecting theapplymethod to be used, whenPoint(1, 2)is what callsapply. - Using a different spelling or case for the object name, so it is a separate object rather than the companion.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: