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 Answers
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>
2 Comments
forpas
array.requireNoNulls() is safer to use in what sense? It throws an
IllegalArgumentException if there are any null elements.Suryavel TR
@forpas Good catch. I have updated the answer. Thanks!
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()
1 Comment
Suryavel TR
question says without copying it.
filterNotNull creates new ArrayList and adds Non-Null values to that before returning it.
mapNotNull().toArray()?