Programming in Kotlin - Part 31: Lists | Ray Wenderlich

Learn how to use Lists in Kotlin to store an ordered collection of data.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4736-programming-in-kotlin/lessons/31

Hi Kev and all,

I have the following code. But when I remove from the list, it does not get removed inside a function. What is that I am missing here? Thanks in advance.

Regards,
Rajesh

fun main() {

var nameList = mutableListOf<String>()
var nameArray = arrayOf("Good","Great","Fine")
nameList.addAll(nameArray)
nameList.add("Bad")
nameList.add("Ugly")

var ptrToList : ( List) → Int =:: printAllNames

//printAllNames(nameList)
ptrToList(nameList)
println("\n ----------------------")
ptrToList(nameList)

}
fun printAllNames( mylist : List ) : Int {
for (name in mylist) {
if (name == “Ugly”) {
var itemToRemove = mylist.indexOf(name)
mylist.drop(itemToRemove)
println("Index: $itemToRemove ")
}
}
println(mylist)

return 0

}

My first thought is that you can’t remove items from a list while in a for loop. If you create an iterator you can remove the item from the iterator. I think the easiest solution is:

val newList = nameList.filter{it != "Ugly"}
1 Like

First of all thank you for the quick response!!!

Ok got it now. Also it appears that if I do filter it then it has to be stored on a NEW list rather than the same list. Why is that? :slight_smile:

Reason I am asking because I have created a pointer like this ‘var ptrToList : ( List) → Int =:: printAllNames’

So when I remove an item from the function it should remove it?

Thank you and looking forward to your clarification.

That is the way that the filter function works. A lot of these types of method try to not change the original list but just return a new one.
If you just want to remove you can try something like this. (Not tested):

val iterator = nameList.asIterable()
    while (iterator.hasNext()) {
        if (iterator.next() == "Ugly") {
            iterator.remove()
        }
    }
1 Like

That worked great! Thank you!! I think doing this way will be faster comparing to copying the result to a new list and then returning it and that’s why I wanted to acheive this method.

Also great timing on response. Enjoying the course so far. Nice work! Thanks Kevin! :slight_smile:

Glad to hear it worked and that you liked the course!

1 Like