Kotlin / api-guidelines

Best practices to consider when writing an API for your library

Home Page:https://kotl.in/api-guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The example on avoiding arrays is incorrect because Enum.values() performs a defensive copy.

LouisCAD opened this issue · comments

## Avoid arrays in public signatures
Arrays are always mutable, and Kotlin is built around safe –read-only or immutable– objects. If you have to use arrays
in your API, copy them before passing them anywhere so that you can check that they have not been modified.
As an alternative, use read-only and mutable collections according to your intentions. Generally, it is best to avoid
using arrays and be very cautious if you need to use them.
For example, enum classes in Kotlin have the `values()` function that returns an array of all elements of the enum.
If the array is not copied, a user is able to rewrite elements:
```kotlin
enum class Test { A, B }
fun main() { Test.values()[0] = Test.B }
```
If you cache values inside the enum, the cache will be corrupted after running the code above. If the values are not cached,
it's an additional runtime overhead for each call of the `values()` function.

This topic can be rephrased better, indeed.

The underlying point is to avoid arrays, because otherwise authors are forced to make a defensive copy (and that's not that great -- it's hard to reason about in the long run; this is exactly the reason Enum.values() is deprecated for good). We should shift focus to that point rather than "do a defensive copy otherwise"

Of course, we meant to say, "If enum would return not a defensive copy, then… And defensive copies might be expensive."