lundi 28 janvier 2019

Using a kotlin clause with enums instead of multiple if

I am working with the next code:

  override fun presentNativeItem(dcsItem: DCSItem?): Any {
        if (dcsItem?.type == "NavMenu") {
            return buildNavMenu(dcsItem)
        } else if (dcsItem?.type == "NavLink") {
            return buildNavLink(dcsItem)
        } else if (dcsItem?.type == "Image") {
            return buildImage(dcsItem)
        }
        else throw IllegalStateException("Unknown Type ${dcsItem?.type} of NavItem")
    }

But instead of using multiple if, I would like to use the next enum:

enum class DSCType {
    NAVMENU,
    NAVLINK,
    IMAGE;

    override fun toString(): String {
        return this.name.toLowerCase()
    }

    companion object {
        fun fromString(value: String?): DSCType? {
            return when (value?.toLowerCase()) {
                "NavMenu" -> NAVMENU
                "NavLink" -> NAVLINK
                "Image" -> IMAGE
                else -> null
            }
        }
    }
}

Any ideas of how can I achieve that in the kotlin way?

Thanks

Aucun commentaire:

Enregistrer un commentaire