Companion object and function extension

Any update on where we are with being able to have companion extension functions even if the receiving class has no companion object?

I just wrote an “extension” for KClass called forName() that works correctly even if the name represents one of the Kotlin primitive classes. However, since KClass has no companion object I ended up creating my own class called KClassCompanion and put a companion object on that. So, I have KClassCompanion.forName(), which will work and is somewhat intuitive.

However, this feels like a band-aid on a band-aid. There is no forName() equivalent and then when I try to write one it is ironically not pretty in a language whose stated goal is the opposite. The irony is that extension functions are called statically but it is not possible to use them statically. TBH, I somewhat question replacing simple static methods with a companion object because it appears to give rise to other issues and it is not clear to me what problem the companion object solves in the first place.

Or am I missing something?

1 Like