Inspectopedia
 
2024.3

Companion object in extensions

Warning
New
Last modified: 03 December 2024

Reports incorrect companion objects' usage in extensions.

Kotlin companion object is always created once you try to load its containing class, and extension point implementations are supposed to be cheap to create. Excessive classloading in plugins is a huge problem for IDE startup.

Bad pattern:

Here KotlinDocumentationProvider is an extension registered in plugin.xml:

In this example JavaDocumentationProvider will be loaded from disk once someone just calls new KotlinDocumentationProvider().

Kotlin companion objects in extension point implementation can only contain a logger and simple constants. Other declarations may cause excessive classloading or early initialization of heavy resources (e.g. TokenSet, Regex, etc.) when the extension class is loaded. Note, that even declarations marked with @JvmStatic still produce an extra class for the companion object, potentially causing expensive computations.

Instead of being stored in companion object, these declarations must be top-level or stored in an object.

Move the declaration to top-level:

Before:

After:

Use INSTANCE fieldName in plugin.xml:

Before:

After:

New in 2023.3