1

I have a general enum implementation with traditional key-value attributes:

enum class FooEnum(val key : String, val value : Any) {
    FOO1("FOO_KEY", "FOO_VALUE"),
    FOO2("FOO_KEY2", 0);

    companion object {
        fun getKeyValuesMap(): Map<String, Any> {
            val defaults = HashMap<String, Any>()

            for (v in values())
                defaults[v.key] = v.value

            return defaults
        }
    }
}

Is there a better "Kotlin" way to achieve the same result of getKeyValuesMap() ?

2 Answers 2

4
fun getKeyValuesMap() = FooEnum.values().associate { it.key to it.value }
Sign up to request clarification or add additional context in comments.

2 Comments

I did a mixup of both answers: val map = FooEnum.values().associate { it.key to it.value }
Yes, that's better than my answer.
0
mapOf(*values().map { foo -> foo.key to foo.value }.toTypedArray())

I'd consider using a val instead of fun, the drawback is that someone could in theory cast the result to MutableMap or HashMap and mutate it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.