2 Change companion object name

Companion object was introduced to replace static members. It is not only for declaring static properties but also to name them. How? Let’s have a look at this example.

// Using in Java CustomButton button = new CustomButton(context); button.setVisibility(CustomButton.Companion.getGONE()); // Using in Kotlin val button = CustomButton(context) button.visibility = CustomButton.VISIBLE class CustomButton(context: Context?) : View(context) { companion object { // Visibility val GONE = 1 val VISIBLE = 2 val INVISIBLE = 3 } }

By default, Kotlin creates a static nested class Companion for every companion object. That is why you need to use CustomButton.Companion to access static members from Java code(you can also use it in Kotlin but it is not necessary). Kotlin lets you change the default name of companion object to whatever name you want. Refactored code looks like this.

// Using in Java CustomButton button = new CustomButton(context); button.setVisibility(CustomButton.Visibility.getGONE()); ... class CustomButton(context: Context?) : View(context) { companion object Visibility { val GONE = 1 val VISIBLE = 2 val INVISIBLE = 3 } }

The biggest drawback is that Kotlin does not support multiple companion objects for a class. It would be great for grouping static properties.

val button = CustomButton(context) button.visibility = CustomButton.Visibility.VISIBLE button.foregroundGravity = CustomButton.ForegroundGravity.LEFT class CustomButton(context: Context?) : View(context) { companion object Visibility { val VISIBLE = 1 val INVISIBLE = 2 } companion object ForegroundGravity { val LEFT = 1 val RIGHT = 2 } }

Note : This code does not compile because Kotlin supports only one companion object per class.

You must read : What is Disadvantage or Cons of Kotlin?