https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

Nat Strangerweather

03/11/2022, 6:27 PM
Hi, hope this is the right place. I am trying to loop through a list of Strings so that I can create an array called Letter which is made of a String and an Int. The problem is that whatever I do, I only ever get the last value of my list of Strings. What could I be doing wrong?
Copy code
fun savedData(): Array<Letter> {
        val arr = mutableStateOf(boardLetters)
        if (savedValues != null) {
            for (item in savedLetters!!) {
                arr.value = Array(28) {
                    Letter(item, 0)
                }
            }
        }
        return arr.value
    }
For info: boardLetters is this:
boardLetters: Array<Letter>
Thanks for any help.
l

Luke

03/11/2022, 6:54 PM
The problem is that you assign
arr.value
to an array for each
savedLetters
, so you replace the array each iteration, keeping the last in the end
I'm guessing what you want is something like:
Copy code
fun savedData(): Array<Letter> {
    return savedValues?.map { Letter(it, 0) }
        ?.toTypedArray()
        ?: arrayOf()
}
n

Nat Strangerweather

03/11/2022, 7:08 PM
Thank you so much! 👍
I also have a list of savedValues for each savedLetters. How can I add them instead of the 0?
l

Luke

03/11/2022, 8:32 PM
savedValues
is a list with corresponding index, a map, or something else?
n

nkiesel

03/11/2022, 8:37 PM
Copy code
fun savedData(savedLetters: List<String>, savedValues: List<Letter>): List<Letter> {
    return savedLetters.map { l -> Letter(l, savedValues.find { it.letter == l }?.value ?: 0) }
}
or - better if savedValues can become long -
Copy code
fun savedData(savedLetters: List<String>, savedValues: List<Letter>): List<Letter> {
    val m = savedValues.associateBy(Letter::letter)
    return savedLetters.map { l -> m.getOrDefault(l, Letter(l, 0)) }
}
n

Nat Strangerweather

03/11/2022, 8:44 PM
Thanks a lot, I'm in a call but will check it out after. Cheers! 🙂
n

nkiesel

03/11/2022, 8:48 PM
Copy code
fun savedData(savedLetters: List<String>, savedValues: List<Letter>): List<Letter> {
    return with(savedValues.associateBy(Letter::letter)) { savedLetters.map { get(it) ?: Letter(it, 0) } }
}
if you like one-liners...
note that this assumes that
Letter
is immutable. If that is not the case, you must return new letters:
Copy code
fun savedData(savedLetters: List<String>, savedValues: List<Letter>): List<Letter> {
    return with(savedValues.associateBy(Letter::letter)) { savedLetters.map { Letter(it, get(it)?.value ?: 0) } }
}
n

Nat Strangerweather

03/11/2022, 9:19 PM
Thanks again, that very helpful!
2 Views