I have the following emun class to represent my navigation bar views.
enum class NavigationPosition(val position: Int, val id: Int) {
HOME(0, R.id.nav_home),
SEARCH(1, R.id.nav_search),
PROFILE(2, R.id.nav_profile),
SETTINGS(3, R.id.nav_settings);
}
I'm currently using the following method to do a reverse lookup by position
fun getByPosition(position: Int): NavigationPosition = when (position) {
0 -> NavigationPosition.HOME
1 -> NavigationPosition.SEARCH
2 -> NavigationPosition.PROFILE
3 -> NavigationPosition.SETTINGS
else -> NavigationPosition.HOME
}
var navigationPosition = getByPosition(position)
Is there a simpler way I can refactor getByPosition
by using a Kotlin lambda or extension function?
As already mentioned, you can use NavigationPosition.values()
. However, the current ways proposed are NOT memory efficient. The values function creates a new array every time it is called. I highly recommend you cache it in a static variable to make sure it's not initialized every time you call it, as this isn't efficient.
Combining a comparative approach with a cached approach, you can use a companion object inside the enum. Now, like I said, caching the values is the best option here, so in addition to a method (as mentioned in both the other answers), you also create a field containing the values, to avoid re-calling it every time you call the method.
companion object {
private val values = values()
fun getPositionById(id: Int) = if(id < values.size && id >= 0) values[i] else HOME
}