Hi, Can anyone explain this please? I am expecting...
# getting-started
n
Hi, Can anyone explain this please? I am expecting here to print a list of letters with the letter on which I clicked removed. Instead, what I get is "true".
Copy code
fun removeUsedLetters() {
        val boardLetters = readBoardLetters.value!!.toMutableList()
        val newList = boardLetters.remove(letter.value)
        println("remaining = $newList")
    }
Why does
remove()
act as a Boolean, and how can I get each letter that I click on to be removed from my list?
j
remove()
is a mutating operation, it doesn't return a new list. It actually does remove the element from the mutable list, but its return value is a boolean telling you whether or not the element was actually found and removed (true) or if the list didn't have the element and thus wasn't changed (false). If you want to return a new list, you can use the
-
operator instead:
Copy code
val newList = boardLetters - letter.value
Note that in this case there is no point in converting your original list into a mutable one with
toMutableList()
. Also note that this operation will not change
readBoardLetters
.
🙏 2
n
Thank you for the explanation. I have tried to obtain a new list in the way that you suggest, but the element comes back when I click on a new one. I wanted the list to actually remove each letter one by one as I click on them. The idea is that I will then know when all the letters have been used... That's why I decided to use remove() as I understand it to be a "write" operation... Any ideas?
e
.toMutableList()
returns a mutable copy of the list, so any changes to
boardLetters
has no effect on
readBoardLetters.value
. what is
readBoardLetters
?
k
And the general documentation on kotlin lists (read-only and mutable)
👍 1
n
readboardLetters
is a list of letters on the gameBoard and they are saved in a room database.
I don't actually want to change that
I just want to know if all letters have been clicked.
j
It's hard to understand whether you want to modify the original list or not. If you want to keep the original but also track the clicked letters, then you should keep a second collection (probably a set) of letters that were clicked (or that remain to be clicked). (But that additional collection should be declared outside
removeUsedLetters()
if you want to access the same collection everytime)
👍 1
n
Thanks, yes, it's the latter. I'll try to work out what you suggest! 😊
Actually, that's what I've been trying to do. I am trying to remove the letters that have been clicked from the list of letters so I know which ones remain.