Search code examples
kotlinkotlin-null-safety

Create Array without nullable types from Array with nullable types


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?


Solution

  • 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>