Kotlin Enums — Replace values() with entries
Make use of Kotlin 1.9.0 updates to improve performance…
Kotlin enums provides a values
method that returns an array of all enum entries BUT it has some issues….
What’s wrong with 'values()' method
?
1- It allocates and clones an Array on each invocation, making it a common source of performance bugs.
2- It returns Array<E>
which is mutable by default and is less flexible to work with than any collection forcing users to manually convert arrays to lists.
3- Since it returns Array<E>
it’s hard to write any special extension functions for enums.
Solution
Kotlin introduced entries
value to retrieve enum entries instead of values()
method. which has the following advantages…
1- It returns a pre-allocated list (it return always the same list)
2- It’s immutable.
3- It returns EnumEntries<E>
which extends List<E>
, so we can use all of the list interface’s functions/extensions + we can write custom extensions for enums for e.g
fun <E : Enum<E>> EnumEntries<E>.someExtension(): E {...}
enum class RGB{
RED, YELLOW, ....
}
val x: RGB = RGB.entries.someExtension()
Note:
entries
was introduced in1.8.20
as an experimental feature but it’s now stable in Kotlin1.9.0
Useful resources
That was it and I hope you loved the blog ❤️