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

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:

  1. Companion Objects
Syntax
scala
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

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. #}
Common Mistakes
  1. Putting the companion object in a different file from the class, when it must be in the same file to share private members.
  2. Calling new Point(1, 2) and expecting the apply method to be used, when Point(1, 2) is what calls apply.
  3. 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:

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.