Let say I have some values in a List. I would like to return another list with a new element
fun newList():List<Int>{
val values =listOf<Int>(1,2,3,4,5,6);
return 7::values; // something like that
}
Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.
We have three methods to add new elements to a list: append , insert , and extend . An empty list is created. The append method adds an item at the end of the list; we append two strings. The insert method places an element at a specific position indicated by the index number.
The items in the outer list are List<int> objects. In the first line, you create the outer list. In the second line, you create a list of int and add it as one of the items in the outer list. In the third line, you add an integer to the first inner list in the outer list.
The Kotlin lists have the plus
operator overloaded in kotlin-stdlib
, so you can add an item to a list:
val values = listOf(1, 2, 3, 4, 5, 6)
return values + 7
There's also an overload that adds another list:
val values = listOf(1, 2, 3, 4, 5, 6)
return listOf(-1, 0) + values + listOf(7, 8)
Note that in both cases a new list is created, and the elements are copied into it.
For MutableList<T>
(which has mutating functions, in contrast with List<T>
), there is a plusAssign
operator implementation, that can be used as follows:
fun newList(): List<Int> {
val values = mutableListOf(1, 2, 3, 4, 5, 6)
values += 7
values += listOf(8, 9)
return values
}
A different approach by using spread operator. Maybe in some case would be simpler than using +
sign or mutableListOf
fun newList(): List<Int>{
val values = listOf(1,2,3,4,5,6)
return listOf(7, *values.toTypedArray(), 8, 9)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With