Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Throughout this lesson, you’ll learn:

  • When to use enum classes in your project.
  • How to define enum classes.
  • How to use enum classes in code.

How Do You Declare Enum Class?

Enum classes provide a way to represent a fixed set of constants within a type-safe structure. They help you define a collection of related constants distinct from each other. You can declare an enum class using the enum class keyword followed by the name of the class:

enum class DayOfWeek {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
enum class ErrorType {
  NOT_FOUND, INVALID_INPUT, SERVER_ERROR
}
enum class DropdownOption {
  OPTION_BANANA, OPTION_APPLE, OPTION_GRAPE
}
fun main() {
  val currentSelection = DropdownOption.OPTION_BANANA
  println("Current selection: $currentSelection")
}

Reason of Using Enum Class

There are a few reasons to use enum classes.

fun createFruitBox(fruitBox: String): FruitBox {
  return when (fruitBox) {
    "Banana" -> Banana()
    "Apple" -> Apple()
    "Grape" -> Grape()
    else -> throw IllegalArgumentException("Invalid fruit")
  }
}
enum class Fruits {
  BANANA,
  APPLE,
  GRAPE
}

fun createFruitBox(fruitBox: Fruits): FruitBox {
  return when (fruitBox) {
    Fruits.BANANA -> Banana()
    Fruits.APPLE -> Apple()
    Fruits.GRAPE -> Grape()
    else -> throw IllegalArgumentException("Invalid fruit")
  }
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo