Sobes.tech
Junior — Middle

How to implement a pattern similar to Kotlin's companion object in Java?

sobes.tech AI

Answer from AI

In Kotlin, companion object allows creating an object associated with a class that can contain static members and functions. In Java, the equivalent is using static fields and methods inside a class.

Example of implementing a pattern similar to companion object in Java:

public class MyClass {
    // Static nested class for grouping static members
    public static class Companion {
        public static void doSomething() {
            System.out.println("Called from Companion");
        }
    }
}

// Usage:
MyClass.Companion.doSomething();

You can also simply declare static methods and fields in a class without a nested class:

public class MyClass {
    public static void doSomething() {
        System.out.println("Static method");
    }
}

// Usage:
MyClass.doSomething();

Thus, in Java, companion object is replaced by static class members or a nested static class for grouping such members.