Ask Your Question
0

What is the procedure to alter Enum properties by extracting dataclass?

asked 2023-05-25 16:13:52 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-25 16:28:02 +0000

plato gravatar image

To alter Enum properties by extracting data class, you can follow these steps:

  1. Create a data class with the properties you want to extract from your Enum:
data class MyDataClass(val value1: String, val value2: Int)
  1. Add a companion object to your Enum and define a function that returns an instance of your data class for each enum value:
enum class MyEnum {
    VALUE1 {
        override fun getDataClass(): MyDataClass {
            return MyDataClass("value1", 1)
        }
    },
    VALUE2 {
        override fun getDataClass(): MyDataClass {
            return MyDataClass("value2", 2)
        }
    };

    abstract fun getDataClass(): MyDataClass
}
  1. Use the getDataClass() function to access the data in your Enum:
val data1 = MyEnum.VALUE1.getDataClass()
val value1 = data1.value1 // "value1"
val value2 = data1.value2 // 1
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-25 16:13:52 +0000

Seen: 19 times

Last updated: May 25 '23