Jumping through hoops in Kotlin with uninitialized arrays


I normally want to reserve array space in Kotlin but because each element is a complex class with prerequisite classes as constructor arguments so I don’t want to initialize the array up front as it’s too messy. So the only way to declare an uninitialized array, near as I can tell, is to put nulls in each element when declared. Unfortunately to do this the array elements are nullable types throughout the rest of the code and I have to jump through hoops to reconcile the nullable type with the non-nullable type. Kotlin doesn’t recognize the nullable type as having any of the interfaces or abstract methods that my non-nullable type has. This seems quite silly to require immediate initialization of an array when declared. This is a desktop application and I use this language because of its succinct syntax but things are not so clean and succinct if I have to always jump through hoops every time I want to reserve uninitialized array space.

Anyone have any suggestions on how to handle non-initialized arrays without nullable types in Kotlin or how to succinctly reconcile these nullable array elements with the non-nullable types at the point of initialization and use? Thanks.

Depending on which order you initialize these elements using a List or a Map<Int, YourObject> seems more appropriate.
Or you can iteratively fill your array with nullables and at the end convert that to a List<YourObject> with out ?, that takes fundamentally no time.

1 Like

Kotlin generally discurages the use of arrays in favour of lists, because lists are nearly always more powerful and List is an interface and not a specific class. So unless you have a good reason to prefer using arrays you should just switch to lists. That way you get a number of useful utility functions from the standard library, eg. buildList - Kotlin Programming Language.

If you really have to use arrays you can create it using a temp array and then later caste it to it’s non-null version. Or if this is something you have to use often I’d suggest building your own function for it – based on the buildList function I linked above.


1 Like

Thank you! I guess a List it is. However as I know the exact array size ahead of time, a List didn’t seem appropriate.

In most cases it does not matter. If you really care about performance and you know the array size you can create the list yourself insetad of calling mutableListOf

val foo: MutableList<Bar> = ArrayList(50)

That way the internal buffer of the list is created with the specified size.

One big advantage I forgot above is that with Lists you get both List and MutableList allowing you to restrict your data to a readonly view.

1 Like