Kotlin ‘Enum.values()’ is recommended to be replaced by ‘Enum.entries’
2 min readDec 5, 2023
Kotlin 1.9.2 introduced a new feature Enum.entries. What is it, and why is it preferred over Enum.values()?
How do Enum.values() work?
Enum.values()
It creates a New Mutable Array every time you use it.
- Every time it is called, a new array is created, which can lead to performance issues if not used properly.
- It returns an Array, which you probably will want to convert into a list, which leads to even more computing.
- It’s mutable, which is something you might not expect, and leads to hard-to-fix bugs.
val values = Enum.values() // Can affect performance if too many arrays are created
values[0] = Enum.TWO // Array is mutable meaning it's easy to introduce unexpected bugs
In this example, a new array is created and then one of its elements is replaced.
How do Enum.entries work?
Enum.entries
It returns a Constant Immutable List.
- It works faster because we don’t need to copy the array we access a defined constant.
- It’s a List instead of Array, which lets us use all the Collection extensions without creating a List.
- It’s immutable, which is something you would expect when accessing enums.
val entries = Enum.entries // Returns a constant Immutable List
entries.add(Enum.TWO) // Compilation error
entries[0] = Enum.TWO // Compilation error
Thanks for reading. If it helped you in some way, please give me a 👏. It will help others find the article! Happy coding!
Article based on: