Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading