Issue
I'm new in Kotlin, and got this case for my project.. I have this example of array :
items: [
{name: "item A", quantity: "9"},
{name: "item B", quantity: "2"},
{name: "item C", quantity: "4"},
]
and i have an object that i want to add to items[ ]
new_object: {name: "item AA", quantity: "4"}
Can anyone help me, how to do it in Kotlin...? Thank you before..
Solution
Well, you can use both MutableList and ArrayList for this case.
First of all, you will need to define the structure for your items
data class Item(
val name: String,
val quantity: String
)
Then you initialize the list
val items = mutableListOf(
Item("Item A", "1"),
Item("Item B", "2"),
Item("Item C", "3"),
)
// Or
val items = arrayListOf(
Item("Item A", "1"),
Item("Item B", "2"),
Item("Item C", "3"),
)
And finally, when you want to append your item to the array you can do it like this
val newItem = Item("Item D", "4")
items.add(newItem)
Complete code will look like this:
data class Item(
val name: String,
val quantity: String
)
val items = mutableListOf(
Item("Item A", "1"),
Item("Item B", "2"),
Item("Item C", "3"),
)
val newItem = Item("Item D", "4")
items.add(newItem)
Answered By - michael.grigoryan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.