However I’m not sure we have to introduce a companion for every class in the standard library. It looks like an overkill, if all what those companions are going to provide is to be a receiver for static-like extensions. Also there are a bunch of java classes which could benefit from having such extensions.
Maybe we should allow having companion extensions without requiring companion classes to exist at all?
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.
Why would you need this. It seems like you just using a class as a namespace for top-level function. It seems like this could just be top-level function scoped using the file.
I created something like this for serialization in a module:
internal fun Long.Companion.fromByteArray(byteArray: ByteArray): Long {
val buffer = ByteBuffer.wrap(byteArray)
return buffer.getLong(0)
}
Now, I need to do the same thing for LocalDate (which has no Companion), and it doesn’t work. As a workaround, I created the extension function to the KClass, but it’s looks ugly to rely on reflection API to achieve that.
Any update here? Being able to create extension functions at this level without companion object would be great.
On my side I work on Toothpick/KTP, a DI framework. By having this feature, the runtime performance and complexity of the generated code would improve drastically.
This would be a great feature, making it comfortable to avoid namespace pollution.
As it stands now, we cannot rely on the existence of companion classes.