Hi everyone, I have this simple code and it doesn'...
# getting-started
d
Hi everyone, I have this simple code and it doesn't run as expect. I want to add an element to an array of int and then I expect it will have 1 element. The current code print 0
Copy code
val res : Array<Int>  = emptyArray()
 res.plus(1)
 println(res.size)
p
Kotlin arrays are fixed-size length so you shouldn’t be able to add anything to an empty array.
d
Thanks Paula. What is the mutable data structure I should use here.
p
Calling the
plus()
function seems to create a new empty array (hence why it’s not throwing an error).
You can use
listOf()
, which is immutable but not fixed length so you can add more elements to it. If you really need mutable, there is
mutableListOf()
d
Got it. Using listOf works with plus , whereby using mutableListOf works with add. I should use
add
in my use case.
p
Ah sorry, I wasn’t quite right: arrays are fixed-length, but mutable. So if you create an emptyArray, it can only ever have 0 elements. Similarly, an array of size 3 can only have 3 elements. But you can change the elements in the array, e.g.
myArray[1] = 2
(as long as you obey the array type).
Lists
are immutable but you can create a new list by using
plus
, which would generally be safer / preferable as you aren’t modifying the original list.
val newList = oldList.plus(1)
ImmutableLists
are less safe (something else could be modifying your list at the same time) so it’s generally preferable to use an immutable list.
d
Yeah, I guess array is something from Java. So it is mutable.
and it is fixed size. To use dynamic size, it is Arraylist
r
Copy code
Val res = mutableListOf<Int>()
res += 1
println(res.size)  // 1