3

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:

image

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

Edit:

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

This code fails, too.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ice1000
  • 6,406
  • 4
  • 39
  • 85

1 Answers1

5

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.

Todd
  • 30,472
  • 11
  • 81
  • 89