One Face
One Face

Reputation: 427

How do I access a enum instance using its property in Kotlin?

I have a enum class like this:

enum class ParkingLotStatus (val number:Int, var occupied: Boolean) {
        LOT1(1,true),
        LOT2(2,false)
    }

I want to select the enum instance using the number variable. If I get user input as 1, I want to be able to pick the enum intense LOT1 based on the variable (constant?) number.

One way would be to iterate over all the enum instances and check if the input matches the variable

Is there a more simple and not resource intense way to do this?

Upvotes: 0

Views: 1013

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170745

In case you do need to do this often, initializing the map is easy enough:

enum class ParkingLotStatus (val number:Int, var occupied: Boolean) {
    LOT1(1,true),
    LOT2(2,false);
    companion object {
        private val map = values().associateBy { it.value }
        fun byValue(number: Int): ParkingLotStatus? = map[number]
    }
}

The problem is, lookup in a hashmap can actually slower than iterating a small array. The simple and reliable improvement would be to store the values array:

enum class ParkingLotStatus (val number:Int, var occupied: Boolean) {
    LOT1(1,true),
    LOT2(2,false);
    companion object {
        private val allValues = values()
        fun byValue(number: Int): ParkingLotStatus? = allValues.find { it.number == number }
    }
}

Upvotes: 1

Mohamed Alsaid
Mohamed Alsaid

Reputation: 960

Something like this would work:

fun main(args: Array<String>) {
    val parking = ParkingLotStatus.get(1) // LOT1
}
enum class ParkingLotStatus (var occupied: Boolean) {
    LOT1(true),
    LOT2(false);
    companion object {
        fun get(number: Int) = when(number){
            1 -> LOT1
            2 -> LOT2
            else -> throw UnsupportedOperationException("Invalid parking number")
        }
    }
}

I would also suggest switching over to sealed classes over Enums

Upvotes: 2

curioustechizen
curioustechizen

Reputation: 10672

Using enumValues() and iterating through them is pretty much the way to go. If you measure the performance impact of iterating through you're likely to discover that it is not that expensive, especially considering that you're not going to have too many enum constants.

You could maintain a map of (number, enumValue) pairs, but I'm willing to bet that the performance gain is not worth the added maintenance effort of updating this map every time anything about the enum values changes.

Upvotes: 1

Related Questions