Home > Mobile >  How to compare string with enum values and return corresponding enum value in Kotlin
How to compare string with enum values and return corresponding enum value in Kotlin

Time:11-04

    var stringValue: String = "ort"

How to compare stringValue with nameOfCode from Data enum class and get get corresponding code value from enum class in Kotlin in android.

enum class Data(val nameOfCode: String, val code: String) {
    WES("wes", "6"),
    ORT("ort", "70"),
    R("R", "7"),
    RON("Ron", "6,7"),
    LO("Lo", "6,70"),
    OT("ot", "7,70"),
    ALL("All", "6,7,7000")
}

Eg: Here string value is "ort" so in enum ort corresponding code value is "70". How to get this value.

CodePudding user response:

You can find the corresponding entry in the enum and get its code, like this:

val code = Data.values().find { it.nameOfCode == nameToBeSearched }?.code

This will give null if nameToBeSearched does not match with any nameOfCode in the enum.

  • Related