Kotlin: eliminate nulls from a List (or other functional transformation)
you can also use
mightContainsNullElementList.removeIf { it == null }
You can use filterNotNull
Here is a simple example:
val a: List<Int?> = listOf(1, 2, 3, null)
val b: List<Int> = a.filterNotNull()
But under the hood, stdlib does the same as you wrote
/**
* Appends all elements that are not `null` to the given [destination].
*/
public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(destination: C): C {
for (element in this) if (element != null) destination.add(element)
return destination
}