Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two Enums,

enum class EnumKey

enum class EnumValue

and I already have a mapping from EnumKey to EnumValue.

fun EnumKey.toEnumValue(): EnumValue = 
    when(this) {
    EnumA.KEY1 -> EnumValue.VALUE1
    EnumA.KEY2 -> EnumValue.VALUE2
    ...
    ...
    EnumA.KEY1000 -> EnumValue.VALUE1000
    }

Now I need to have an another mapping from EnumValue to EnumKey.

Is using a Map and its reversed map created by associateBy the best way to do it? Or is there any other better ways?

Thanks!

question from:https://stackoverflow.com/questions/65661066/how-to-effectively-map-between-enum-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
163 views
Welcome To Ask or Share your Answers For Others

1 Answer

If the enum values are somehow connected by name and they're as large as in your example, then I would advise using something like EnumValue.values().filter { it.name.contains(...) } or using regex.

If they aren't and the connection needs to be stated explicitly then I would use an object (so it's a singleton like the enums themselves) and have this mapping hidden there:

object EnumsMapping {

    private val mapping = mapOf(
        EnumKey.A to EnumValue.X,
        EnumKey.B to EnumValue.Y,
        EnumKey.C to EnumValue.Z,
    )
....

and next, have the associated values available by functions in this object like:

fun getEnumValue(enumKey: EnumKey) = mapping[enumKey]

and

fun getEnumKey(enumValue: EnumValue) = mapping.filterValues { it == enumValue }.keys.single()

If it's often used or the enums are huge, and you're troubled by the performance of filtering the values every time, then you can create the association in the second way, just like you've proposed:

private val mapping2 = mapping.toList()
        .associate { it.second to it.first } 

and then have the second function just access this new mapping.

Writing the extension functions like you've provided, but using this object, will result in cleaner code and having the raw association still in one place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...