Arrays are often used as maps in the case where you have a relatively small number of integer keys. It seems like it would be useful to have a getOrPut
method similar to that available for maps. The only interesting nuance I can think of here is that arrays have index bounds to worry about. So beyond a getOrPut
that throws for invalid indices, maybe we would also want a getOrNullOrPut
(name suggestions welcome…) that returns null for invalid indices.
I’m not exactly sure what is your expected behavior here. Arrays don’t have a concept of not existing items, so they always return a value. They also can’t “put” new items. Array is a collection of say 5 items, all of them exist and can be replaced by another value. This is pretty much it.
Also, arrays aren’t used much in general Kotlin programming.
They’re needed for low-level implementation, for interoperability with Java and libraries, and can be used if you have really tight memory requirements. But they’re inferior to Lists in many ways: they don’t work well with generics (e.g. you can’t create an array of a generic type), they can’t be resized, the standard library provides less support for them, they have only a single implementation which can’t be overridden so no way to customise the performance or provide a decent toString() method, no support for multi-threading…
If you don’t have any of the speciaist requirements above, it’s usually better to use a List instead. (You can always create an explicit ArrayList if you need the specific behaviour and performance of an array, though it’s almost always better to use a List reference thereafter, just in case.)
This is a problem, not the lack of getOrPut.