Search code examples
intellij-ideakotlincompanion-object

Internal Objects for Utility Classes?


I used IntelliJ's Kotlin to Java conversion tool to convert a Java Utility Class (all class methods are static, it can't be instantiated) to Kotlin.

IntelliJ created an internal object of the form:

internal object MyObject {  
    const val FIELD1: String = "constant string"

    fun myStaticFn(): String {
        return "hi"
    }
}

How is this different from making a class with a companion object?


Solution

  • I agree with what JB Nizet said that is avoids creating unnecessary class, and there is one more benefit which is usage of internal which means you won't expose that utility class in case your project is to be used as dependency for some other project. Of course there are cases when you would like to have a library with some helpful utility methods and in such situation you could remove internal modifier, but in many other cases it's better to provide only nice and clean API, while hiding utility methods that you are using.