How can I write extension methods for Array's Companion obejcts in Kotlin?

As we know (mentioned in this question, countless people writing the same answer), we can have extension methods for companion objects to make something look like a "static extension".

But when I tried this on kotlin.Array, I failed:

operator fun <T> Array<T>.Companion.invoke() {

The code above causes this error:


So does Arrays have companion objects? If no, how can I make "static extension"s for Arrays?


inline operator fun <reified T> Array<T>.Companion.invoke() {

This code fails, too.

1 answer

  • answered 2018-03-11 13:44 Todd

    You cannot do this in Kotlin currently. The core problem with adding this here is that kotlin.Array does not currently have a companion object, and you can't add an extension on a companion object that does not exist.

    According to this thread, there is no way to add a extension function to a companion object that does not exist, but people are asking for it.

    The best answer in that thread I can find is from @yole:

    This feature is not on the roadmap for Kotlin 1.2; we haven’t done any planning for subsequent versions yet.

    Edit: I found KT-11968, which seems to cover this case and has some interest from other people. Perhaps lobby for that to be included in some future release? Note that I found several other issues that seemed to fit this description but were all marked duplicates of KT-11968, so I think that's the one to upvote/lobby.