How can I tell Kotlin that an array or collection cannot contain nulls?

前端 未结 3 1247
野趣味
野趣味 2021-01-20 15:03

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

        
3条回答
  •  日久生厌
    2021-01-20 15:45

    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"}
    

提交回复
热议问题