PoisonedYouth
09/07/2022, 7:21 AMval result = myList
.filter { it.nullableProperty != null }
.map { it.nullableProperty!!.fromAccount }
Why do I have to use the non-null asserted call in the map step?Joffrey
09/07/2022, 7:29 AMfilter
is generic and has the same type of element as output. The condition in the filter leads to a smart cast within the filter lambda, but that smart-cast type doesn't make it out.
This is why the stdlib introduced filterNotNull
for exactly this purposeSzymon Jeziorski
09/07/2022, 7:30 AMfilter
does not change generic arguments type as shown by its signature:
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>
Looking at your code you can achieve what you need explicitly calling map
and then `filterNotNull`:
val result = myList
.map { it.nullableProperty }
.filterNotNull()
.map { it.fromAccount }
But in your use case mapNotNull
with safe access to fromAccount
would fit perfectly achieving exactly the same:
val result = myList.mapNotNull { it.nullableProperty?.fromAccount }
Roukanken
09/07/2022, 7:51 AMfromAccount
is non-nullable; otherwise first one could return null, and second wouldn't)Szymon Jeziorski
09/07/2022, 7:55 AMPoisonedYouth
09/07/2022, 7:56 AMPoisonedYouth
09/07/2022, 7:56 AM