https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dan

09/05/2020, 9:41 AM
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

Paula Muldoon

09/05/2020, 9:45 AM
Kotlin arrays are fixed-size length so you shouldn’t be able to add anything to an empty array.
d

dan

09/05/2020, 9:46 AM
Thanks Paula. What is the mutable data structure I should use here.
p

Paula Muldoon

09/05/2020, 9:47 AM
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

dan

09/05/2020, 9:53 AM
Got it. Using listOf works with plus , whereby using mutableListOf works with add. I should use
add
in my use case.
p

Paula Muldoon

09/05/2020, 9:59 AM
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

dan

09/05/2020, 10:05 AM
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

Ruckus

09/05/2020, 3:32 PM
Copy code
Val res = mutableListOf<Int>()
res += 1
println(res.size)  // 1