Hello,
I have a questions regarding transformation of list:
Copy code
val 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?
j
Joffrey
09/07/2022, 7:29 AM
This is because
filter
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 purpose
s
Szymon Jeziorski
09/07/2022, 7:30 AM
because
filter
does not change generic arguments type as shown by its signature:
Copy code
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`:
Copy code
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:
Copy code
val result = myList.mapNotNull { it.nullableProperty?.fromAccount }
➕ 2
🙌 1
r
Roukanken
09/07/2022, 7:51 AM
(those two would have same result only if
fromAccount
is non-nullable; otherwise first one could return null, and second wouldn't)
s
Szymon Jeziorski
09/07/2022, 7:55 AM
@Roukanken whoops, you're absolutely right, probably didn't have to rush so much with the comment :)