Create Array without nullable types from Array with nullable types

611 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

array.requireNoNulls() returns same array Array<T?> with non-optional type Array<T> (But throws IllegalArgmentException if any of the item found null).

if you are sure that your array doesn't have null then you can typecast.

array as Array<String>

1
On

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()