CodeBlanks Logo Icon CodeBlanks

enum class

Learn to define named constants with enum class.

enum class: named constants

An enum class defines a fixed set of values. Each constant has a name; a typo is caught at compile time. It is ideal for colors, directions, days of the week.

enum class Color { RED, GREEN, BLUE }
val c = Color.RED
println(c)  // RED

Constants are separated by commas inside braces. To access one, write Color.RED. You use a meaningful name instead of a number, which improves readability.

Accessing an enum constant

To access a constant, write ClassName.CONSTANT. A constant is an object; the name property returns its name.

val r = Color.RED
println(r.name)  // "RED"
println(r)       // RED

Comparing two constants with == is safe; each constant is a single object. name always returns the name as declared. This gives you consistent output in logs or interfaces.

Practice Define the Signal enum

Define an enum class called Signal with RED, YELLOW, GREEN. In main print the Signal.YELLOW constant with println.

Starter code

Main.kt
fun main() {
    // Define a signal type and print one constant
}

Sample solution

Main.kt
enum class Signal { RED, YELLOW, GREEN }

fun main() {
    println(Signal.YELLOW)
}

Expected output

YELLOW

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What kind of values does an enum class hold?

  • Random numbers
  • Named constants Correct answer
  • Dynamic text
  • File paths

Explanation: Each constant has a name; the compiler checks them.

2 Fill in the blank: enum constant

Question
val c = Color.____
Answer
val c = Color.RED

Explanation: Color.RED accesses the constant.

3 Match constant to meaning

Term Meaning
RED Red
GREEN Green
BLUE Blue
name Constant name

All lessons in Beginner