Companion objects are an effective way to scope properties and methods to an enclosing class and to mimic the behavior of static properties and methods from Java. Unfortunately, the syntax for working with companion objects can be cumbersome when used from Java. In this section, we'll take a look at how to work effectively with companion objects.
Better companions
How do companion objects work?
When a companion object is declared within a Kotlin class, the compiler will generate an inner class named Companion during compilation. Here, we've defined an empty companion object on a Widget class:
class Widget {
companion object { }
}
From the preceding code snippet, the following Java code is generated by the compiler...