Ian Medeiros
Ian Medeiros

Reputation: 1776

Extract Map<String, Object> from enum with key-value attributes in one line?

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() ?

Upvotes: 1

Views: 1840

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

fun getKeyValuesMap() = FooEnum.values().associate { it.key to it.value }

Upvotes: 4

Alexey Romanov
Alexey Romanov

Reputation: 170723

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.

Upvotes: 0

Related Questions