Companion Objects
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: