This is a question about language design rather than trying to solve a specific problem.
I noted two oddities about object instances inside companion objects:
- object instances can't be referenced without the
.Companion
- object instances cannot be annotated @JvmStatic
As shown below, neither constraint applies to functions defined within companion objects. The distinction for apparently for what appear to be sibling declarations is a bit of mental overhead I'd rather not have to deal with.
Is there an example that demonstrates why these constraints were necessary? Presumably for Java interop, but I have yet to think of the case.
class MyClass {
companion object {
@JvmStatic
fun myFunc() {}
//@JvmStatic // Error: This annotation is not applicable to target 'standalone object'
object MyObject {}
}
}
fun testingReferencing() {
MyClass.myFunc()
MyClass.Companion.myFunc() // Awkward and redundant, but works.
//val obj1 = MyClass.MyObject // Error: Unresolved reference: MyObject
val obj2 = MyClass.Companion.MyObject
}