Sobes.tech
Junior — Middle

What bytecode is generated for declaring a companion object in Kotlin when compiling into a Java project?

sobes.tech AI

Answer from AI

In Kotlin, during compilation to JVM bytecode, the declaration of companion object is transformed into a static nested class named Companion. This class contains all members of the companion object as regular methods and fields.

In Java code, access to the members of the companion object is done via a reference to the static field Companion of the outer class.

Kotlin example:

class MyClass {
    companion object {
        fun foo() = "Hello"
    }
}

The compiled bytecode will include a class MyClass$Companion with the method foo(), and in MyClass there will be a static field Companion of type MyClass$Companion.

In Java, it looks like this:

MyClass.Companion.foo();

Thus, the companion object is implemented as a singleton of a nested class accessible via a static field.

What bytecode is generated for declaring a companion… - sobes.tech