https://kotlinlang.org logo
Title
o

oday

07/08/2021, 9:41 AM
I would like to append an element to an IntArray, how would I do it in something simpler than this?
var result = intArrayOf(1, 2, 3, 4)

val list = result.toMutableList()
list.add(5)

result = list.toIntArray
a

Albert Chang

07/08/2021, 9:50 AM
intArrayOf(1, 2, 3, 4) + 5
😮 4
👍🏻 1
o

oday

07/08/2021, 9:55 AM
wat
i really didnt know you could do that
e

ephemient

07/08/2021, 11:06 AM
also
intArrayOf(1, 2, 3, 4) + intArrayOf(5)
it's all just wrapping the creating of a new array and copying, no magic involved…
t

Tobias Berger

07/09/2021, 11:35 AM
so in your case it could also be
result += 5
c

CLOVIS

07/11/2021, 9:38 AM
Do note that these solutions will copy the array. If you want to append an element often with good performance, use ArrayList (which will essentially do the same thing but is more clever about what and when to copy, so it's much much faster)
👍 1
e

ephemient

07/11/2021, 11:23 AM
agreed. mutableListOf()/.toMutableList()/etc. are implemented by ArrayList so you are safe to just use those as normal
but there is no unboxed list built into Kotlin, so there may be some cases where primitive arrays are useful
c

CLOVIS

07/11/2021, 1:02 PM
Primitive arrays are a very slight bit faster, but if you need to append elements they are slower. In practice the difference in performance is so small between ArrayList and Array that in 99% of cases it's not worth using primitive arrays.
e

ephemient

07/11/2021, 8:07 PM
trove4j does have primitive (unboxed) lists that have amortized growth just like ArrayList (and of course you could build your own). there are cases in which that is actually worth it over the boxing of ArrayList. but yeah, most of the time MutableList<Int> is fine
c

CLOVIS

07/11/2021, 10:17 PM
Ah, I didn't get that you mentioned boxing as in Ints being boxed, I thought you meant the whole array being boxed (in the ArrayList instance), which is really damn cheap. If you have a really big array of primitives, the memory difference can be important, yeah. Hopefully Valhalla will solve all of this though.