Operator overload spread operator


#1

Just a question.
Is there a reason that the spread-operator is not overridable?
Or that it is only added to arrays?


#2

The semantics of the spread operator cannot actually be implemented in an overloaded function. Add to that the fact that adding an operator is easy, removing one is an incompatible language change and every feature adds a cost to the language. I’m afraid that it’s insufficient to have yet another operator to (mis)use in your dsl.


#3

Vote it


#4

If you require the operator to be an inline function that returns an Array<out …>, where the compiler will spread in turn, then it should be possible right?

If it’s to difficult, it would be great to see that List, Sequence, and Map (Pair<K,V>) would implement it…
(I never really accounted something other than those ones)


#5

So what you want to achieve is something like

functionTakingVarArgs(*myList)

working? I think that can be handled simply enough by something like

functionTakingVarArgs(*myList.toArray())

which wouldn’t warrant another language feature.


#6

What the operator actually does is take an array value and use the elements of that array as parameters to a function. What it seems the intent here is to somehow have a type that you want the spread operator return a custom array for which it would apply the spread operator. One thing to take into account here is that such a custom array would be a temporary with its values wrapped in another array that is the parameters to the vararg (this is what the compiler currently does if you present it an array). Like @Jonathan.Haas says, you can easily use a function that returns such an array, also making explicit that there is this temporary array creation involved.

What could be an interesting addition would be to define the spread operator for Iterable types (perhaps with specialisations for optimization on some types). This would not work as creating a temporary array though, it would be adding code to the compiler to handle that case (the same way that in Java the foreach loop has an array and an Iterable implementation)