🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Companion Objects

A companion object is an object with the same name as a class. It sits beside the class and holds makers and shared values for it.

A maker builds class values

The puppy maker in the companion object builds a Dog with age 0. The caller passes only the name.

class Dog(val name: String, val age: Int)

object Dog:
  def puppy(name: String): Dog = Dog(name, 0)

@main def main(): Unit =
  val pup = Dog.puppy("Pip")
  println(pup.name)
  println(pup.age)

A companion holds shared constants

The sound and legs values belong to every dog, so they live in the companion object. They are read through the class name.

class Dog(val name: String, val age: Int)

object Dog:
  val sound = "Woof"
  val legs = 4

@main def main(): Unit =
  val rex = Dog("Rex", 3)
  println(Dog.sound)
  println(Dog.legs)
  println(rex.name)

Makers can offer fixed settings

Each maker fills in both fields with fixed settings. The two calls build coffees with different sizes and sugar counts.

class Coffee(val size: String, val sugar: Int)

object Coffee:
  def small(): Coffee = Coffee("small", 1)
  def large(): Coffee = Coffee("large", 2)

@main def main(): Unit =
  val first = Coffee.small()
  val second = Coffee.large()
  println(s"${first.size} ${first.sugar}")
  println(s"${second.size} ${second.sugar}")

Example

class Book(val title: String, val pages: Int)

object Book:
  val store = "City Books"
  def shortStory(title: String): Book = Book(title, 40)

@main def main(): Unit =
  val book = Book.shortStory("The Hill")
  println(Book.store)
  println(book.title)
  println(book.pages)

Key points

  • Companion object: an object that shares its name with a class in the same program.
  • Maker: a def in the companion object that builds and gives back a class value.
  • Fixed settings: a maker can fill in field values, so callers pass only the values that change.
  • Shared constant: a value that belongs to the whole class, stored once in the companion object.
  • Access: makers and constants are used through the shared name, like Dog.puppy or Dog.sound.

In this example, the Book companion object holds a shared store name and a shortStory maker. The maker builds a Book with the given title and a fixed count of 40 pages. The prints show the shared name first, then the title and page count of the built book.

Note

the class makes the values, and the companion object holds the helpers that belong to all of them.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

A maker def that builds values of a class is usually written where?