Kotlin basics - Enum

Kotlin basics - Enum

Lets start understanding the Enum with basic structure

enum class BatteryState{
    EXCELLENT ,
    GOOD ,
    AVERAGE,
    LOW
}

The enum values can be accessed as following

val batteryStateFromAPI = "low"
val batteryState  = BatteryState.valueOf(batteryStateFromAPI.toUpperCase())
println(batteryState)

output : 
LOW

Enum constructors

We can add constructor to enum as following

enum class BatteryState(val batteryRange : String){
    EXCELLENT ("90-100"),
    GOOD ("50-89"),
    AVERAGE("16-49"),
    LOW("<15 - please charge");
}

The enum constructor can be helpful,as following snippet

val batteryStateFromAPI = "low"
val batteryState  = BatteryState.valueOf(batteryStateFromAPI.toUpperCase())
 println("$batteryState - ${batteryState.batteryRange}")

output : 
LOW : <15 - please charge

Enum with abstract functions

enum class BatteryState(val batteryRange: String) {
    EXCELLENT("90-100") {
        override fun getBatteryDisplayStatus(): String {
            return "Battery is ${EXCELLENT.name} : ${EXCELLENT.batteryRange}%- remaining 12hrs"
        }
    },
    GOOD("50-89") {
        override fun getBatteryDisplayStatus(): String {
            return "Battery is ${GOOD.name} : ${GOOD.batteryRange}% - remaining 8hrs"
        }
    },
    AVERAGE("16-49") {
        override fun getBatteryDisplayStatus(): String {
            return "Battery is${GOOD.name} : ${AVERAGE.batteryRange}%- remaining 4hrs"
        }
    },
    LOW("<15 - please charge") {
        override fun getBatteryDisplayStatus(): String {
            return "Battery is ${GOOD.name} : ${LOW.batteryRange}% -  please charge"
        }
    };

    abstract fun getBatteryDisplayStatus(): String
}

This abstract fun getBatteryDisplayStatus(): String helps in writing up some logic for each eunm we have defined .

The access and output as follows

 val batteryStateFromAPI = "good"
 val batteryState = BatteryState.valueOf(batteryStateFromAPI.toUpperCase())
 println(batteryState.getBatteryDisplayStatus())

output:
Battery is GOOD : 50-89% - remaining 8hrs

Tip: Iterate over Enum values :

 BatteryState.values().forEach {
        println("$it : ${it.batteryRange}")
   }

output : 
EXCELLENT : 90-100
GOOD : 50-89
AVERAGE : 16-49
LOW : <15 - please charge

So finally , I hope i made somebody understand enum in kotlin.

Please leave your comments to improve.

Enjoy coding , untill next time