Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin immutable arrays

Tags:

arrays

kotlin

Kotlin lists come in separate mutable and immutable varieties, where the former is derived from the latter. But as I understand it, with arrays, there is no separate immutable type per se; instead, an immutable array is declared like Array<out Foo>.

Is this correct?

If so, what's the reason for array and list types being designed differently in that regard?

like image 419
rwallace Avatar asked Jan 25 '23 01:01

rwallace


1 Answers

This is correct, Arrays are all mutable, there's no separate read-only interface for arrays.

The reason for this is that arrays are low-level building blocks that should not normally be exposed in the API or passed across encapsulation boundaries, and in general, there's no reason to use arrays over lists outside data structure implementations and, sometimes, performance-critical code. One should prefer lists and other collections for higher-level operations.

So, given that arrays are usually encapsulated and 'owned' by a single, consistent piece of logic, it was not so practical to introduce a separate type for arrays that doesn't expose mutating functions.

like image 81
hotkey Avatar answered Feb 01 '23 20:02

hotkey