What are 'Companion Objects' in Scala?

Instruction: Explain the concept of companion objects in Scala and their common use cases.

Context: This question is designed to test the candidate's understanding of companion objects, their relationship with Scala classes, and their typical uses, such as factory methods and static members.

Updated

A companion object is an object with the same name as a class or trait, defined in the same source file. The companion and its class can access each other's private members. Common uses include factories, extractors, shared constants and type-class instances. Companion objects

final class Quantity private (private val amount: BigInt) {
  def label: String = s"${Quantity.prefix}$amount"
}
object Quantity {
  private val prefix = "quantity="
  def from(amount: BigInt): Either[String, Quantity] =
    if (amount < 0) Left("Quantity must be nonnegative")
    else Right(new Quantity(amount))
  def value(quantity: Quantity): BigInt = quantity.amount
}
@main def companionExample(): Unit = {
  assert(Quantity.from(-1).isLeft)
  val result = Quantity.from(3)
  assert(result.map(Quantity.value) == Right(BigInt(3)))
  assert(result.map(_.label) == Right("quantity=3"))
}

The factory controls ordinary construction through a private constructor, and the example shows private access in both directions. An apply factory can provide Name(arguments) syntax; in Scala 3, ordinary classes can also use universal apply syntax, so omitting new is not proof of a hand-written companion factory.

The object is not an instance of the companion class, and declaring it does not make all class instances a singleton. Scala objects offer a natural location for members that resemble Java static utilities, with JVM interoperability details handled by the compiler. Shared mutable state inside an object still needs an appropriate concurrency policy.

Related Questions