1

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?

1
  • How about mapNotNull().toArray()? Commented Nov 21, 2018 at 12:32

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

array.requireNoNulls() is safer to use in what sense? It throws an IllegalArgumentException if there are any null elements.
@forpas Good catch. I have updated the answer. Thanks!
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()

1 Comment

question says without copying it. filterNotNull creates new ArrayList and adds Non-Null values to that before returning it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.