Kotlin Enums: Replace values() with entries
Article Summary
Ilyas Ipek from Teknasyon reveals a hidden performance killer in Kotlin that most Android devs hit daily. That innocent enum.values() call? It's silently allocating and cloning arrays every single time.
Kotlin 1.9.0 introduced a stable replacement for the problematic values() method on enums. The old approach created performance bugs through repeated allocations and returned mutable arrays that were clumsy to work with. The new entries property solves all three major pain points.
Key Takeaways
- values() allocates and clones a new array on every call
- entries returns a pre-allocated, immutable list (always the same instance)
- EnumEntries<E> extends List<E>, enabling custom enum-specific extensions
- Feature stable in Kotlin 1.9.0 after experimental phase in 1.8.20
Switching from enum.values() to enum.entries eliminates repeated allocations, provides immutability, and unlocks better API design for enum operations.
About This Article
Kotlin's values() method on enums returns a mutable Array<E>, which means developers have to manually convert arrays to lists. This makes it hard to build flexible APIs and add custom enum-specific functions.
Ilyas Ipek at Teknasyon Engineering suggests using the entries property instead. It returns EnumEntries<E>, which extends List<E>. This lets developers write custom extension functions like fun <E : Enum<E>> EnumEntries<E>.someExtension(): E.
The entries property became stable in Kotlin 1.9.0, after being experimental in 1.8.20. It provides immutability and uses consistent pre-allocated list instances, so you don't need to clone arrays every time you call it.