9

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?

2
  • 2
    What would the difference be between an immutable list and an immutable array? Commented May 10, 2020 at 15:42
  • @LouisWasserman I would expect a small difference in efficiency (list needs to allocate an extra object as well as the underlying array) and in the case where it's a parameter, the ability to take an array as an argument (e.g. vararg). Commented May 10, 2020 at 17:06

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Immutable Arrays are now available:

https://github.com/daniel-rusu/pods4k/tree/main/immutable-arrays

Surprisingly, they are much faster than lists and quite a bit faster than regular arrays for many common operations due to many optimizations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.