kotlin
Add new items to Array in Kotlin
In this post, we are going to describe different methods that can be used to add items to an array using Kotlin. We will be converting our arrays to mutable type to add new item.
fun main() {
var names = arrayOf<String>("James", "Walter", "Roy", "Salve")
val namesList = names.toMutableList()
namesList.add("Rick")
namesList.add("Carol")
names = namesList.toTypedArray()
println(names.contentToString())
}
Output
[James, Walter, Roy, Salve, Rick, Carol]
In the above code snippet,
- We have declared an array called names. We want to add new items to this array.
- We are converting the array to a mutable list using the toMutableList() function and adding the item to this mutable list using add() function.
- After adding the item we are converting the mutable list to an array using the toTypedArray() function.
Use ArrayList() and add items
You can use ArrayList in place of arrayof() while creating the function. When using an ArrayList, we can use its add() function to add an item to this array list. We can also iterate over the Array list using Kotlin For loop.
fun main() {
val arr = ArrayList<String>()
arr.add("Nick")
arr.add("John")
arr.add("Rick")
print(arr)
}
Output
[Nick, John, Rick]
Loop through ArrayList()
fun main() {
val arr = ArrayList<String>()
arr.add("Nick")
arr.add("John")
arr.add("Rick")
for (item in arr) {
println(item)
}
}
Output
Nick
John
Rick
Use Arrays.copyOf() to add an item to array
We can use Arrays.copyOf() function to add a new element to the array in Kotlin. The copyOf() function will create a copy of the array with the additional item on the last. Then we are replacing that item with our new item value.
fun <T> addItemToArr(inputArr: Array<T>, item: T): Array<T?> {
val result = inputArr.copyOf(inputArr.size + 1)
result[inputArr.size] = item
return result
}
fun main() {
var nums = arrayOf<Int?>(10, 20, 30, 40)
nums = addItemToArr(nums, 50)
println("Final array elements are:")
for (item in nums) {
print(item.toString() + " ")
}
}
Output
Final array elements are:
10 20 30 40 50
val fruits = mutableListOf<String>("Apple", "Banana", "Orange")
fruits.add("Mango")
println(fruits)
// -> [Apple, Banana, Orange, Mango]
You can also create a mutable list and add items to it. The mutable list has a function add() where we can pass our item and it will be added to the list. The mutable list is also iterable.
Was this helpful?
Similar Posts