Given this code: ```println(intArrayOf() === intAr...
# stdlib
k
Given this code:
Copy code
println(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.
e
that's what
newarray
does in java
btw arrays are rather special in Java, in that they know their own component type (although erased, because it predates generics):
Copy code
arrayOf<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)
if for some reason you really do need a single empty array per type, you can handle that yourself. https://pl.kotl.in/eSSlzXEfC but it should be understandable why it's not something standard or built-in
👍 1
but in general, just don't use arrays.
emptyList()
is a singleton (not that it even needs to be to pass
emptyList<Int>() == emptyList<Int>()
, since it has structural
equals
)
👍 1