-2

I am new to kotlin and I am having trouble making array of objects and inserting values index by index in it, currently I am declaring and inserting values like this but the app is getting crashed without any error.

 val array = arrayOf<User>()
        array[0] = User("name1", "address1")
        array[1] = User("name2", "address2")
        array[2] = User("name3", "address3")
  • 1
    `but the app is getting crashed without any error.` that's unlikely – a_local_nobody Oct 20 '21 at 13:28
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Oct 20 '21 at 13:28

1 Answers1

4

Arrays have fixed size. arrayOf<User>() creates an empty array and you can't add any items to it. You can create an array with provided users with the following:

val array = arrayOf(
    User("name1", "address1"),
    User("name2", "address2"),
    User("name3", "address3"),
)

If you know how to construct items for each index then you can use this alternative:

val array = Array(3) { index ->
    User("name${index + 1}", "address${index + 1}")
}

If you need a data structure with growing size, then use MutableList instead:

val list = mutableListOf<User>()
list += User("name1", "address1")
list += User("name2", "address2")
list += User("name3", "address3")
broot
  • 21,588
  • 3
  • 30
  • 35
  • what would be correct syntax to add the values if I have the size of array? – Faizan Yousaf Oct 20 '21 at 13:37
  • I added one more example, using `Array(3)`. Note that array can't hold just nothing. If you create array of size 3, you need to provide these 3 elements immediatelly. Items could be nulls, but then array will be `Array`. But anyway, is there any reason to choose arrays over lists? If not then I suggest using lists. They are preferable in most cases. – broot Oct 20 '21 at 13:41