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
