Home > other >  How to declare an empty array without expecting null in Kotlin?
How to declare an empty array without expecting null in Kotlin?

Time:09-02

So I have my code like this

var items = arrayOfNulls<String>(20)

Clearly I mentioned <String>, not <String?> . In the next code, I add bunch of string values to my items variable, but when I convert my items variable to list of string, I got error mismatch type that my items variable is detected as <String?>. Here is my conversion code.

val texts: List<String> = items.toList()

I can change my texts declaration into List<String?> to avoid the error, but that's not what I wanted. I want my texts variable data type is List<String>. Turns out the root caused is I expected null value during my items declaration and it changed the data type from <String> to <String?>. But how to declare an ampty array without expecting null?

CodePudding user response:

The signature of the arrayOfNulls function:

fun <reified T> arrayOfNulls(size: Int): Array<T?>

enforces a nullable <T?> no matter if you put a type without a question mark. Notice that it returns Array<T?> so even if the T you pass is non-nullable, the Array returned has a nullable type.

This makes perfect logical sense. It is giving you an array that contains null values.

An "empty" array is an array with 0 length. If you want an array with a non-zero length but no values in it, then it has to be filled with nulls. There's no other logical possibility.

This is a limitation of Arrays. You may want to use a MutableList instead, or if you already know what you're going to put in the array, use the array constructor that takes an initialization lambda for how to initially fill it.

For your specific situation, an alternate solution might be (suitability depends on what you're doing with it):

val texts: List<String> = items.filterNotNull()

CodePudding user response:

The name says it arrayOfNulls : Nulls.

Whatever type you indicate will be a nullable type. If you want an empty String array just do

var items = arrayOf<String>()
  • Related