Sobes.tech
Junior — Middle

What is the result of compiling a companion object in Kotlin in relation to Java code?

sobes.tech AI

Answer from AI

In Kotlin, a companion object is compiled into Java as a static nested class within the outer class. All members of the companion object become static methods and fields of this nested class.

For convenience in calling from Java, a static field named Companion is created in the outer class, through which you can access the members of the companion object.

For example, Kotlin code:

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

Compiles roughly to Java as:

public final class MyClass {
    public static final MyClass.Companion Companion = new MyClass.Companion(null);

    public static final class Companion {
        public final String foo() {
            return "Hello";
        }
    }
}

Thus, from Java, you can call the method like:

String greeting = MyClass.Companion.foo();

If @JvmStatic annotations are declared in the companion object, then the corresponding methods and fields will be generated as static members of the outer class, allowing them to be called directly without referring to Companion.

What is the result of compiling a companion object in… - sobes.tech