Skip to content
Related Articles

Related Articles

Enum Classes in Kotlin
  • Last Updated : 11 Jul, 2019

In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants.
In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that something has a number of possible values. Unlike Java enums, Kotlin enums are classes.

Some important points about enum classes in kotlin –

  • Enum constants aren’t just mere collections of constants- these have properties, methods etc
  • Each of the enum constants acts as separate instances of the class and separated by commas.
  • Enums increases readability of your code by assigning pre-defined names to constants.
  • An instance of enum class cannot be created using constructors.

Enums are defined by using the enum keyword in front of class like this:-

enum class DAYS{
  SUNDAY,
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY
}

Initializing enums –

In Kotlin also enums can have a constructor like Java enums. Since enum constants are instances of an Enum class, the constants can be initialized by passing specific values to the primary constructor.

Here is an example to specify colors to cards –



enum class Cards(val color: String) {
    Diamond("black"),
    Heart("red"),
}

We can easily access the color of a card using –

val color = Cards.Diamond.color

Enums properties and methods –

As in Java and in other programming languages, Kotlin enum classes has some inbuilt properties and functions which can be used by the programmer. Here’s a look at the major properties and methods.

Properties –

  1. ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.
  2. name: This property stores the name of the constant.

Methods –

  1. values: This method returns a list of all the constants defined within the enum class.
  2. valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown.

Example to demonstrate enum class in Kotlin –




enum class DAYS {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
}
fun main()
{
    // A simple demonstration of properties and methods
    for (day in DAYS.values()) {
        println("${day.ordinal} = ${day.name}")
    }
    println("${DAYS.valueOf(" WEDNESDAY ")}")
}

Output:

0 = SUNDAY
1 = MONDAY
2 = TUESDAY
3 = WEDNESDAY
4 = THURSDAY
5 = FRIDAY
6 = SATURDAY
WEDNESDAY

Enum class properties and functions –

Since enum class in Kotlin, defines a new type. This class type can have its own properties and functions. The properties can be given a default value, however, if not provided, then each constant should define its own value for the property. In the case of functions, they are usually defined within the companion objects so that they do not depend on specific instances of the class. However, they can be defined without companion objects also.

Example to demonstrate properties and functions in Kotlin




// A property with default value provided
enum class DAYS(val isWeekend: Boolean = false){
    SUNDAY(true),
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    // Default value overridden
    SATURDAY(true);
   
    companion object{
        fun today(obj: DAYS): Boolean {
            return obj.name.compareTo("SATURDAY") == 0 || obj.name.compareTo("SUNDAY") == 0
        }
    }
}
   
fun main(){
    // A simple demonstration of properties and methods
    for(day in DAYS.values()) {
        println("${day.ordinal} = ${day.name} and is weekend ${day.isWeekend}")
    }
    val today = DAYS.MONDAY;
    println("Is today a weekend ${DAYS.today(today)}")
}

Output:

0 = SUNDAY and is weekend true
1 = MONDAY and is weekend false
2 = TUESDAY and is weekend false
3 = WEDNESDAY and is weekend false
4 = THURSDAY and is weekend false
5 = FRIDAY and is weekend false
6 = SATURDAY and is weekend true
Is today a weekend false

Enums as Anonymous Classes –

Enum constants also behaves as anonymous classes by implementing their own functions along with overriding the abstract functions of the class. The most important thing is that each enum constant must be override.




// defining enum class
enum class Seasons(var weather: String) {
    Summer("hot"){
        // compile time error if not override the function foo()
        override fun foo() {              
            println("Hot days of a year")
        }
    },
    Winter("cold"){
        override fun foo() {
            println("Cold days of a year")
        }
    },
    Rainy("moderate"){
        override fun foo() {
            println("Rainy days of a year")
        }
    };
    abstract fun foo()
}
// main function
fun main(args: Array<String>) {
    // calling foo() function override be Summer constant
    Seasons.Summer.foo() 
}

Output:

Hot days of a year

Usage of when expression with enum class –

A great advantage of enum classes in Kotlin comes into play when they are combined with the when expression. The advantage is since enum classes restrict the value a type can take, so when used with the when expression and the definition for all the constants are provided, then the need of the else clause is completely eliminated. In fact, doing so will generate a warning from the compiler.




enum class DAYS{
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY;
}
   
fun main(){
    when(DAYS.SUNDAY){
        DAYS.SUNDAY -> println("Today is Sunday")
        DAYS.MONDAY -> println("Today is Monday")
        DAYS.TUESDAY -> println("Today is Tuesday")
        DAYS.WEDNESDAY -> println("Today is Wednesday")
        DAYS.THURSDAY -> println("Today is Thursday")
        DAYS.FRIDAY -> println("Today is Friday")
        DAYS.SATURDAY -> println("Today is Saturday")
        // Adding an else clause will generate a warning
    }
}

Output:

Today is Sunday
My Personal Notes arrow_drop_up
Recommended Articles
Page :