I have a method accepting a vararg of the form
fun arrayOfArrays(vararg aoa: Array<Any>) {
}
Now, I have trouble understanding how to call this method, e.g.
fun callArrayOfArrays() {
arrayOfArrays(arrayOf(1), arrayOf(1)) // 0) works
val a = arrayOf(1)
arrayOfArrays(a, a) // 1) type mismatch: inferred type Array, but Array was expected
val aoa = arrayOf(a)
arrayOfArrays(aoa) // 2) type mismatch: inferred type Array<array>, but Array was expected
arrayOfArrays(*aoa) // 3) type mismatch: inferred type Array<array>, but Array<out array> was expected
arrayOfArrays(aoa.toList().toTypedArray()) // 4) works
}
UPDATE: After getting a heads-up by a colleague, we figured that adding types to arrayOf() fixes some of my problems, i.e. the following does work now:
fun callArrayOfArrays() {
arrayOfArrays(arrayOf(1), arrayOf(1))
val a = arrayOf<Any>(1)
arrayOfArrays(a, a)
val aoa = arrayOf<Array<Any>>(a)
arrayOfArrays(*aoa)
arrayOfArrays(aoa.toList().toTypedArray())
arrayOfArrays(*(aoa.toList().toTypedArray()))
}
I still believe that the former should be fine, too. And I do yearn for an understandable explanation for this behavior.
I appreciate that case 0 works, but I fail to understand all the other cases.
For case 1, I would expect that assigning the arrayOf(1) to a variable does not change the semantics, but here we are.
For case 2, I would expect that it works like I would expect the first case to work, just the "Any" being an Array here.
For case 3, I can see the difference, but I do not understand it, and certainly do not know how to ever make this work.
For case 4, I believe this is the vararg taking a single array. However, I cannot spread it either.