JetBrains has detailed upcoming extensions to Kotlin's companion mechanism starting in version 2.5.0. The updates introduce experimental companion blocks and companion extensions designed to improve static member compilation and expand interoperability across multiplatform projects.
Companion Blocks and Static Compilation
Historically, Kotlin relied on companion objects to handle class-level functionality such as factory methods, utilities, and constants. Starting with Kotlin 2.5.0, developers can use a companion block syntax instead. While syntactically similar to companion objects, companion blocks change how the code is compiled. On the JVM, companion blocks compile directly into static members rather than generating intermediate companion object instances. This shift allows developers in Kotlin Multiplatform projects to define expected companion block members in common code and fulfill them using standard Java classes containing static members.
Extending Unowned Classes with Extensions
Kotlin 2.5.0 also introduces experimental companion extensions, which allow developers to declare new static-like members on existing classes or interfaces. This feature applies regardless of whether the target type was originally authored in Kotlin or Java, or whether it already possesses a companion object.
Compiler Flags and Compatibility Limitations
Both features are experimental and require explicit compiler flags. Developers can enable companion blocks using the `-Xcompanion-blocks` flag, while enabling extensions requires `-Xcompanion-blocks-and-extensions`. Using companion extensions causes the compiler to produce pre-release binaries, which prevents libraries using them from being consumed as stable dependencies until the feature stabilizes.
Existing companion objects remain fully supported and are required for scenarios where a companion must implement a specific interface, as companion blocks do not produce a separate class instance. JetBrains states that existing codebases do not require migration, though removing the `object` keyword will transition standard companion objects to companion blocks after recompilation.
AI-generated editorial illustration; not a documentary photograph.
Source: The Companions to Come

Leave a Reply