Home > Software engineering >  How to create an Enum class that takes multiple parameters but only uses one of them for comparison
How to create an Enum class that takes multiple parameters but only uses one of them for comparison

Time:03-04

I want my enum class to take two parameters but only use one of them when comparing which type to initialize. Here I want the id to be passed during initialization as well but not use it to control which type gets created.

enum class ActionEnum(val action: String, val id: String) {
    URL("URL") {
        override fun start() {
            openUrl(id)
        }
    },
    START_FRAGMENT("FRAG") {
        override fun start() {
            startFragmentWithId(id)
        }
    },
    START_POPUP("POPUP"){
        override fun start() {
            startPopUpWithMessage(id)
        }
    };

    open fun start() {
    }
}

CodePudding user response:

From your question is not really clear what you intend to do with the parameter action, but I think that what you are looking for are sealed classes.

Instead of defining an enum, you can define a sealed class like this

sealed class ActionEnum(val action: String, val id: String) {
    class URL(action: String): ActionEnum(action, "URL") {
        override fun start() {
            openUrl(id)
        }
    }
    class START_FRAGMENT(action: String): ActionEnum(action, "FRAG") {
        override fun start() {
            startFragmentWithId(id)
        }
    }
    class START_POPUP(action: String): ActionEnum(action, "POPUP") {
        override fun start() {
            startPopUpWithMessage(id)
        }
    };

    open fun start() {
    }
}

You can use that like an enum which means that e.g. you have exhaustive when without the need for an else clause:

    val a: ActionEnum = ActionEnum.URL("some action")
    when(a) {
        is ActionEnum.URL -> ...
        is ActionEnum.START_FRAGMENT -> ...
        is ActionEnum.START_POPUP -> ...
        // no more cases possible because ActionEnum is sealed
    }

But you can have different instances of each "enum" element where action can have a different value - which is not possible with real enums.

  • Related