Klitos Kyriacou
09/16/2024, 3:12 PMprintln(intArrayOf() === intArrayOf())
We can see that intArrayOf()
creates a new empty array each time it's called. By contrast, in C# the syntax []
is shorthand for Array.empty<>()
which returns a preallocated empty array, thus not needing to do any heap allocation. What is the rationale for making xxxArrayOf()
allocate a new object each time? An empty array is implicitly "immutable" (as there is nothing to mutate), so thread safety is not an issue.ephemient
09/16/2024, 5:41 PMnewarray
does in javaephemient
09/17/2024, 12:14 PMarrayOf<Int>() as Array<Any> // succeeds, but is unsafe to write to because
(arrayOf(0) as Array<Any>)[0] = "" // throws java.lang.ArrayStoreException
arrayOf<Any>() as Array<Int> // throws java.lang.ClassCastException, **not** unchecked
arrayOf<List<Any>>() as Array<List<Int>> // succeeds…
so you cannot have a single static empty array for all types, you need to have one for every type (including every array type)ephemient
09/17/2024, 12:25 PMephemient
09/17/2024, 12:27 PMemptyList()
is a singleton (not that it even needs to be to pass emptyList<Int>() == emptyList<Int>()
, since it has structural equals
)