In Kotlin we have to distinguish between nullable types and not nullable types. Let's say I have an Array<String?>
fom which I know that every value within it is actually not null. Is there an easy way to create an Array<String>
from the source array without copying it?
Create Array without nullable types from Array with nullable types
611 Views Asked by Cilenco At
2
There are 2 best solutions below
1

Array.filterNotNull might be the safer way to do it. But it will create a new Array.
val items: Array<String?> = arrayOf("one", "two", null, "three")
val itemsWithoutNull: List<String> = items.filterNotNull()
array.requireNoNulls()
returns same arrayArray<T?>
with non-optional typeArray<T>
(But throwsIllegalArgmentException
if any of the item foundnull
).if you are sure that your array doesn't have
null
then you can typecast.array as Array<String>