https://kotlinlang.org logo
#announcements
Title
# announcements
p

pavlospt

06/26/2017, 9:36 AM
hello, so i was trying to find a more elegant way to write the following:
selectedChoices.mapIndexed { index, isSelected -> if (isSelected) index else -1 }.filter { it != -1 }
. Is there a prettier way to write this ? 🙂 In short what I want to do is get the indexes from
selectedChoices
, which is a BooleanArray, where the value is
true
and then map those indexes in something different, hence the
.filter { it != -1}
(also not sure if I am on the right channel)
m

marcinmoskala

06/26/2017, 9:58 AM
pavlospt:
Copy code
booleanArrayOf(true, true, false, true).withIndex().filter { it.value }.map { it.index }
booleanArrayOf(true, true, false, true).toList().mapIndexedNotNull { index, v -> if (v) index else null }
p

pavel.talanov

06/26/2017, 2:37 PM
I'd go with
Copy code
selectedChoices.mapIndexedNotNull { index, isSelected -> index.takeIf { isSelected } }
👍 2
p

pavlospt

06/26/2017, 2:48 PM
Hmm that one seems pretty nice as well! Thanks!
2 Views