https://kotlinlang.org logo
Title
n

Nat Strangerweather

03/16/2022, 4:30 PM
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".
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

Joffrey

03/16/2022, 4:34 PM
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:
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

Nat Strangerweather

03/16/2022, 4:41 PM
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

ephemient

03/16/2022, 4:51 PM
.toMutableList()
returns a mutable copy of the list, so any changes to
boardLetters
has no effect on
readBoardLetters.value
. what is
readBoardLetters
?
k

Kirill Grouchnikov

03/16/2022, 4:51 PM
And the general documentation on kotlin lists (read-only and mutable)
👍 1
n

Nat Strangerweather

03/16/2022, 4:55 PM
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

Joffrey

03/16/2022, 5:00 PM
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

Nat Strangerweather

03/16/2022, 5:01 PM
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.