What is the advantage of "companion object" vs static keyword

I agree–we can’t have a discussion keep redefining each other’s words. When speaking about Kotlin, I use “idiomatic” to mean, “clear and understood naturally”. In case it wasn’t clear, we all want easy-to-understand code.

I think this thread has strayed away from productive, value-based arguments and into unproductive position-based arguments.

Some positions:

  • Static is better than companion objects. Remove companion objects and replace with static.
  • Companion objects are better than statics. Do not change anything.

Our values:

  • Clear, clean, easy-to-understand code (idiomatic Kotlin–using “idiomatic” in the same meaning as it is commonly used in Kotlin)
  • Avoiding language designs that limit our ability to write better code.
  • Including language designs that enable us to write better code.

I suggest we abandon both positions as we share these values in regard to this discussion. The person disagreeing with you also wants beautiful Kotlin code even if they love/hate companion objects.

What are the exact issues people face with companion objects?

  1. Is it the syntax of having to declare things inside the companion object? Would other language changes, such as syntax similar to the following resolve most of the issue for you?
companion fun someCompanionFunction()
  1. Is it a performance issue with companion objects? If the performance was on par with statics, would the issue be mostly resolved?

  2. Is it a scope/namespacing issue? Would other language changes such as something like the following resolve most of the pain points of companion objects?

import top.level.functions.* as Utils // Utils.myTopLevelFunction()
  1. Is it an issue with interoperability (using Kotlin from with Java/JS/Native)?

  2. Is it an issue with writing interoperable code from within Kotlin?

  3. Is the main pain point from previous experience (experience with Java statics)?

I’ve listed all of the root pain points I could think of off the top of my head. Please add any I’ve missed.
Which of these points (or others) would need to be resolved before it would become a non-issue for you?

Rant about this thread

The above are discussion points I would really enjoy discussing and hearing others opinions on. As for statics, Kotlin has companion objects. Let’s identify what pain points exist and if they could be improved (if there are any).

Petitioning for statics is frustrating in that it blocks productive discussion on what the real pain points could be with companion objects.

9 Likes