liveBook · Manning

Companion-object extension

As explained in Kotlin in Action, 2E

A companion-object extension is an extension function or property declared on a class's companion object and callable through the class name.

A companion-object extension adds a function or property to a class's companion object without modifying the class. Declare it with the companion-object receiver, then call it through the class name. section 4.4.3

Keep JSON loading outside the domain class

class Person(val firstName: String, val lastName: String) { companion object } fun Person.Companion.fromJSON(json: String): Person { /* ... */ } val person = Person.fromJSON(json) The empty companion object supplies the receiver for the extension. The implementation can live in a separate business or client/server communication module, while callers retain the concise Person.fromJSON(...) syntax. section 4.4.3

Listing 4.36 Defining an extension function for a companion object
// business logic module
class Person(val firstName: String, val lastName: String) {
    companion object {                                       #1
    }
}
 
// client/server communication module
fun Person.Companion.fromJSON(json: String): Person {        #2
    /* ... */
}
 
val p = Person.fromJSON(json)

Inspect the compact declaration and call site for a companion-object extension. section 4.4.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines the receiver syntax and call site, but does not develop extension dispatch or generated implementation details.
Examples
Uses a Person class, an empty companion object, a fromJSON extension, and a Person.fromJSON call.
What it assumes
Assumes basic Kotlin classes and functions, while demonstrating the companion-object receiver syntax directly.
What you can do after
Builds a class-name factory-style call while keeping its implementation in another module.
How it connects
Connects companion objects with extension functions, JSON serialization, and Java interoperability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.