Take a look at this kotlin one liner:
val nonNullArr : List<NonNullType> = nullArray.filter {it != null}
The compiler gives a type error at this line, saying that a list of nullables can't be assigned to a list of non-nulls. But the filter conditional makes sure that the list will only contain non null values. Is there something similar to !!
operator that I can use in this situation to make this code compile?
To filter collections by negative conditions, use filterNot() . It returns a list of elements for which the predicate yields false . There are also functions that narrow the element type by filtering elements of a given type: filterIsInstance() returns collection elements of a given type.
The simple approach to filtering a MutableList in-place is to iterate through the list using an iterator and remove the list elements using iterator's remove() function. Please note that ConcurrentModificationException will be thrown if remove() function of MutableList is used instead.
You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.
It seems logical to assume that the compiler would take into account the predicate
it != null
and infer the type as
List<NonNullType>
but it does not.
There are 2 solutions:
val nonNullList: List<NonNullType> = nullableArray.filterNotNull()
or
val nonNullList: List<NonNullType> = nullableArray.mapNotNull { it }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With