🔴 Scala Beginner

What is the companion object in Scala?

Answer

A companion object is an object with the same name as a class, defined in the same file. It is Scala's way to have both instance methods and static-like methods. The class and its companion object have access to each other's private members. Common uses: Factory methods: object Person { def apply(name: String) = new Person(name) } — enables Person("Alice") without new. Constants and utilities related to the class. Implicit conversions for the class. Unapply method: enables pattern matching — object Email { def unapply(s: String) = ... }. Case classes get a companion object automatically with apply and unapply generated. Companion objects replace Java's static methods and fields — in Scala, there are no static members on classes.