Scala: Companion Objects

Micah Lewis
Nov 8, 2020

If you’re unfamiliar with Scala then you’ll likely come across and be confused by some code that looks like the following:

case class Rectangle (length: Int, width: Int)object Rectangle {
def area(rectangle: Rectangle) = rectangle.length * rectangle.width
}
val r1 = Rectangle(3, 7)Rectangle.area(r1) //returns 21

Why do we have a class and object of the same name created together in the same file? The answer here is simple. In Scala, you can think of classes and case classes as the data storage, while its companion object is where you should add class methods and constructors.

While it is technically possible to just define the methods and constructors in the class or case class themselves, Scala recommends the use of a companion object for this.

A few other points to wrap up on:

  • Classes and their companion objects have access to each others private values and methods.
  • Classes / case classes and their companion objects must be declared in the same file and have the same name.

As always, if you spot an errors here or have questions, please don’t hesitate to let me know in the comments below.

--

--