If I create an array, then fill it, Kotlin believes that there may be nulls in the array, and forces me to account for this
val strings = arrayOfNulls
A rule of thumb: if in doubts, specify the types explicitly (there is a special refactoring for that):
val strings1: Array = arrayOfNulls(10000)
val strings2: Array = Array(10000, {"string"})
So you see that strings1
contains nullable items, while strings2
does not. That and only that determines how to work with these arrays:
// You can simply use nullability in you code:
strings2[0] = strings1[0]?.toUpperCase ?: "KOTLIN"
//Or you can ALWAYS cast the type, if you are confident:
val casted = strings1 as Array
//But to be sure I'd transform the items of the array:
val asserted = strings1.map{it!!}
val defaults = strings1.map{it ?: "DEFAULT"}