0

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"
)
2
  • 1
    What is this intended for? (For example, if your goal is to write it out as JSON, you'd be better off using a library to do that conversion.) Commented Aug 14, 2020 at 19:28
  • Hi, I'm storing some predefined values in this enum, and the values will be merged with some other dynamic ones into a map to be passed to downstream services Commented Aug 14, 2020 at 19:35

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Sergey, what I really want to achieve is how to not specifically tell what are the keys and values. Like I am able to use gson to transform a data class into a map, I wonder how to do the similar thing with enum
@YIWENGONG I think without reflection we can't do it. Please check my edited answer.
Thanks a lot for this answer!

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.