Kotlin 1.9.0 - Improving Performance with Entries instead of Values() Enum Method

2023/07/10
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

Kotlin enums provide a values() method that returns an array of all enum entries, but it has some issues that can affect performance. Firstly, the method allocates and clones an array on each invocation, which can lead to performance bugs. Secondly, it returns a mutable Array by default, making it less flexible to work with compared to collections. Lastly, writing special extension functions for enums becomes challenging due to the return type of Array.

To address these issues, Kotlin introduced the entries value in version 1.8.20 as an experimental feature. Now, with the release of Kotlin 1.9.0, entries is stable and offers several advantages.

Firstly, entries returns a pre-allocated list, ensuring consistent performance. Secondly, the returned list is immutable, making it easier to work with. Lastly, entries returns EnumEntries, which extends List, allowing developers to utilize all list interface functions and extensions. This also enables the creation of custom extensions for enums.

Developers can now leverage the entries method to improve performance and enhance their code when working with enums in Kotlin.

Useful resources:

  • Official Kotlin documentation on enums: link
  • Kotlin 1.9.0 release notes: link

Written by ilyas ipek, Android developer at Teknasyon Engineering.