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

Companion Objects

In this page:

  1. Companion Objects

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

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)
}
🔒

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.