Hi guys! Do you see a way to reduce this? ```val m...
# random
l
Hi guys! Do you see a way to reduce this?
Copy code
val myList = listOf("A", "AA", "B", "BB")
val aIndices = myList.mapIndexedNotNull { index, str -> if("A" in str) index else null } // 0 and 1
Map indexed not null seems to be a weird solution to this case
Where I need all the indices that match a specific condition
It's like applying
a.filter { predicate }.indices
, but in a way that would work instead of losing the indices
y
While sacrificing performance:
Copy code
myList.withIndex().filter { "A" in it.value }.map(IndexedValue<*>::index)
😮 1
🆒 1
or if you want to keep performance sane enough:
Copy code
myList.mapIndexedNotNull { index, str -> index.takeIf { "A" in str } }
l
Both are prettier options!
That
takeIf
was a nice catch, I forgot about it!