Extend a Class without a Companion


I want to extend Int and IntArray with a “static” function:

fun Int.Companion.foo() = "bar"
val bar = Int.foo()
val zoo = Int.Companion.foo()

fun IntArray.Companion.foo() = "bar"

Unfortunately, this is only working, when the class already contains a companion object to extend. IntArray does not contain a companion object. Is there any workaround possible? Or could the compiler generate an empty companion object for existing classes?

1 Like

There is an issue for that already. However it seems to be quite old. Hopefully this will be implemented in the future.

@Wasabi375 Yes, this is exactly I was looking for. Hopefully, after 4 years, this feature is coming.