YIWEN GONG
YIWEN GONG

Reputation: 141

Construct a Map for each Enum type in Kotlin

I have an Enum class like

enum class Definition(
    val definitionName: String,
    val parameters: Map<String, String>,
    val definitionPath: String = "com/1.0"
) {
    APPLE(
        "this-is-an-apple",
        mapOf("1" to "2")
    ),
    BANANA(
        "this-is-banana",
        mapOf("3" to "4")
    )
}

I would like to construct maps for each enum without specifying the keys and values, like for APPLE

mapOf("definition" to "this-is-an-apple",
      "parameters" to mapOf("1" to "2"),
      "definitionPath" to "com/1.0"
)

Upvotes: 0

Views: 1259

Answers (1)

Sergio
Sergio

Reputation: 30645

If I get it right, you want to map all values of the enum to a list of maps. You can use values() function to go through each item of enum and Kotlin Reflection API:

val maps: List<Map<String, Any>> = Definition.values().map { enumItem ->

    val pairList = mutableListOf<Pair<String, Any>>()

    Definition::class.declaredMemberProperties.forEach { property ->
        val value = property.apply { isAccessible = true }
                        .get(enumItem)
        value?.let { pairList.add(Pair(property.name, it)) }
    }

    mapOf(*pairList.toTypedArray())
}

To use reflection api add next line to the app's build.gradle file dependencies:

implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

Upvotes: 1

Related Questions