Is there a `List<T?> -> List<T>?` m...
# getting-started
m
Is there a
List<T?> -> List<T>?
method (or something similar) in the standard library? Almost like
requireNoNulls
, except I want a function that doesn’t throw.
v
filterNotNull()
will give you
List<T>
if you really want
List<T>?
then you can do something like:
Copy code
fun <T> List<T?>.toNonNullListOrNull(): List<T>? =
    mapNotNull { it ?: return null }
☝🏿 1
e
just
map
, no need for
mapNotNull
👍 1
f
You could also do
Copy code
fun <T> List<T?>.toNonNullListOrNull(): List<T>? = @Suppress("UNCHECKED_CAST") (takeIf { null !in it } as? List<T>?)
which isn't as clean because of the unchecked cast but it doesn't require allocating an entirely new list
e
it is also much more unsafe. the list could change to include a null after, and keeping the same list instance would propagate it to the non-null typed list