Inspectopedia Help

Companion object in extensions

Reports incorrect companion objects' usage in IDE extensions.

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

Bad pattern:

class KotlinDocumentationProvider : AbstractDocumentationProvider(), ExternalDocumentationProvider { companion object { private val LOG = Logger.getInstance( private val javaDocumentProvider = JavaDocumentationProvider() } }

Here KotlinDocumentationProvider is an extension registered in plugin.xml:

<lang.documentationProvider language="JAVA" implementationClass="org.jetbrains.kotlin.idea.KotlinDocumentationProvider" order="first"/>

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

Kotlin companion objects in extension implementations 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.

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


How to rewrite run ConfigurationType?

Move the declaration to top-level:

// DO internal fun mnRunConfigurationType(): MnRunConfigurationType = runConfigurationType<MnRunConfigurationType>() internal class MnRunConfigurationType : ConfigurationType { companion object { // DON'T fun getInstance(): MnRunConfigurationType = findConfigurationType( } }

How to rewrite FileType?


internal class SpringBootImportsFileType : LanguageFileType(SPILanguage.INSTANCE, true) { companion object { val FILE_TYPE = SpringBootImportsFileType() } }


internal object SpringBootImportsFileType : LanguageFileType(SPILanguage.INSTANCE, true) {

Use INSTANCE fieldName in plugin.xml:

<fileType name="Spring Boot Imports" fieldName="INSTANCE" implementationClass="com.intellij.spring.boot.spi.SpringBootImportsFileType"/>

New in 2023.2

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3


Plugin DevKit, 233.SNAPSHOT

Last modified: 13 July 2023