How to create an enumeration of constants with and without explicit values in Kotlin

1 Answer

0 votes
/* 
   Title: Enumeration of Constants in Kotlin
   Example with and without explicit values
*/

enum class Color {
    RED,        // ordinal = 0
    GREEN,      // ordinal = 1
    BLUE        // ordinal = 2
}

// Enum WITH explicit values using constructor parameters
enum class Status(val code: Int) {
    OK(1),          // explicit value 1
    WARNING(5),     // explicit value 5
    ERROR(6),       // explicit value 6
    CRITICAL(10)    // explicit value 10
}

fun main() {
    println("Enum without explicit values:")
    println("RED ordinal = ${Color.RED.ordinal}")
    println("GREEN ordinal = ${Color.GREEN.ordinal}")
    println("BLUE ordinal = ${Color.BLUE.ordinal}")

    println("\nEnum with explicit values:")
    println("OK code = ${Status.OK.code}")
    println("WARNING code = ${Status.WARNING.code}")
    println("ERROR code = ${Status.ERROR.code}")
    println("CRITICAL code = ${Status.CRITICAL.code}")
}


/* 
run:

Enum without explicit values:
RED ordinal = 0
GREEN ordinal = 1
BLUE ordinal = 2

Enum with explicit values:
OK code = 1
WARNING code = 5
ERROR code = 6
CRITICAL code = 10

*/

 



answered Apr 25 by avibootz

Related questions

...