liveBook · Manning

Companion object

A companion object is a singleton object associated with a class or type that provides members associated with the class rather than its instances.

How 2 Manning books explain it

Kotlin in Action, 2E

A companion object is the specially designated object declaration inside a Kotlin class whose members can be accessed through the containing class name.

How it is used
Provides class-associated factories and operations that need private-class access without requiring an instance.
How deep it goes
Defines class-name access, private-constructor factories, naming, interface implementation, and extensions; defers generic details used by the factory example.
Examples
Demonstrates MyClass.callMe(), User creation factories, Person JSON loading, JSONFactory implementation, and a Person.Companion extension.
What you can do after
Apply it via Kotlin class declarations to expose factories, implement interfaces, and attach class-associated operations.

Read how Kotlin in Action, 2E explains companion object →

Functional Programming in Scala, Second Edition

A companion object is a Scala singleton object declared with the same name as a class or other data type and granted access to its private and protected members.

How it is used
Organizes construction and operations for a data type beside its constructors.
How deep it goes
Defines naming, access privileges, variadic construction, and recursive operations without detailing compiler implementation.
Examples
Uses List.apply for construction and List.sum or List.product for recursive pattern-matching operations.
What you can do after
Build it from scratch by defining a matching object with constructors, variadic apply, and operations for a functional data type.

Read how Functional Programming in Scala, Second Edition explains companion object →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.