Hello, I have a questions regarding transformation...
# getting-started
p
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
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
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
(those two would have same result only if
fromAccount
is non-nullable; otherwise first one could return null, and second wouldn't)
s
@Roukanken whoops, you're absolutely right, probably didn't have to rush so much with the comment :)
p
The "fromAccount" property is non-null
Thanks for your explanations