Sobes.tech
Junior — Middle

How is the companion object structure in Kotlin compiled into bytecode?

sobes.tech AI

Answer from AI

In Kotlin, a companion object is compiled into a static nested class within the outer class. During compilation, a separate class is created with a name like OuterClass$Companion, which contains all the members of the companion object as static methods and fields.

Additionally, a static field named Companion is created in the outer class, which references the single instance of this nested class. This allows access to the companion object members via OuterClass.Companion or directly if imported.

Thus, companion object implements a singleton pattern with static members, compatible with JVM, through a separate nested class and a static reference field.