Modifying companion object names

Using companion objects from Java can be cumbersome because of the need to reference the instance of the Companion class. This can lead to Java code that very clearly looks like it's referencing Kotlin code. We can improve this by providing an alternative name for the companion object.

In the following snippet, we've specified Factory as the name of our companion object by adding the desired name after the object keyword:

class Widget {
companion object Factory {
fun create() {}
}
}

With an alternative name specified, the generated class will have the newly specified name. We can then use that new name, Factory, in this case, to reference our companion object and any associated methods or properties:

// Main.java
public class Main {
public static void main(String[] args) {
Widget.Factory.create();
}
}

This allows you to provide greater semantic meaning to your companion objects. If it's being used for factory methods, you may use a name such as Factory. If the companion object will primarily be used for constants, you could name it Constants.

By providing more meaningful names to your companion objects, you can provide greater semantic meaning to your calling code. Additionally, more semantic names can also make it feel more natural to use compared to Java because it hides the companion name, which is an indicator that the code is written in Kotlin.