https://kotlinlang.org logo
Title
r

robstoll

05/05/2018, 10:17 AM
What is the reason that there is only a spread operator for
Array
but not for `Collection`/`Iterable`?
j

janvladimirmostert

05/05/2018, 2:17 PM
you can just call
.toTypedArray()
on a collection, then spread it
r

robstoll

05/05/2018, 4:38 PM
not always unfortunately:
fun <T> foo<T>(l: List<T>) = bar(*l.toTypedArray())
Does not work since T has to be reified (Kotlin needs to know what type the array has)
k

karelpeeters

05/05/2018, 4:51 PM
Spread doesn't really make sense for collections, since it just means "passing an array as a vararg parameter" on the JVM.
r

robstoll

05/05/2018, 5:10 PM
I guess in the end it boils down to the fact that you need to know the type in order to pass it as an array and since you don't always know it, you cannot provide a spread operator in all cases. But then... wouldn't it be possible to provide an operator overload with an reified T. I guess you could. So back to the beginning 🙂 why only array?
k

karelpeeters

05/05/2018, 5:19 PM
Because Lists aren't a language primitive, and providing a dedicated operator for them is ugly.
r

robstoll

05/05/2018, 5:43 PM
so the following should be forbidden:
listOf(1) + listOf(2)
? 😉
k

karelpeeters

05/05/2018, 5:43 PM
I was careful to include "dedicated":
+
is a general overloadable operator.
r

robstoll

05/05/2018, 5:44 PM
I see 🙂, fair enough I guess