Bird
Raised Fist0
Kotlinprogramming~10 mins

Why enums constrain values in Kotlin - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why enums constrain values
Define enum with fixed values
↓
Create variable of enum type
↓
Assign only enum values allowed
↓
Try to assign invalid value?
Yes→Compile error
No↓
Program continues
Enums define a fixed set of values. Variables of enum type can only hold these values. Trying to assign anything else causes an error.
Execution Sample
Kotlin
enum class Direction { NORTH, SOUTH, EAST, WEST }

fun main() {
    var dir: Direction = Direction.NORTH
    // dir = "UP" // Error: Type mismatch
    dir = Direction.EAST
    println(dir)
}
This code shows how a variable of enum type can only be assigned one of the enum's fixed values.
Execution Table
StepActionVariableValueResult
1Define enum Direction--Direction has values NORTH, SOUTH, EAST, WEST
2Declare variable dir of type DirectiondiruninitializedVariable created
3Assign dir = Direction.NORTHdirNORTHValid assignment
4Attempt dir = "UP" (commented out)dirNORTHCompile error if uncommented: type mismatch
5Assign dir = Direction.EASTdirEASTValid assignment
6Print dirdirEASTOutput: EAST
💡 Program ends after printing EAST; invalid assignments are caught at compile time.
Variable Tracker
VariableStartAfter Step 3After Step 5Final
diruninitializedNORTHEASTEAST
Key Moments - 2 Insights
Why can't I assign a string like "UP" to the enum variable dir?
Because enums only allow their predefined values. The execution_table row 4 shows that assigning "UP" causes a compile error since it's not part of Direction.
What happens if I try to assign a value not in the enum?
The program won't compile. The error stops the program before running, as shown in execution_table row 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of dir after step 3?
Auninitialized
BEAST
CNORTH
D"UP"
💡 Hint
Check the 'Value' column in execution_table row 3.
At which step does the program detect an invalid assignment?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table row 4.
If you remove the comment on the invalid assignment, what happens?
ACompile error stops the program
BProgram prints "UP"
CProgram compiles and runs normally
Ddir variable becomes null
💡 Hint
Refer to the 'Result' in execution_table row 4 about compile errors.
Concept Snapshot
enum class Direction { NORTH, SOUTH, EAST, WEST }
- Enums define fixed allowed values.
- Variables of enum type accept only these values.
- Assigning other values causes compile errors.
- Helps prevent invalid data and bugs.
Full Transcript
Enums in Kotlin define a fixed set of named values. When you create a variable of an enum type, it can only hold one of those predefined values. For example, Direction enum has NORTH, SOUTH, EAST, and WEST. If you try to assign a string like "UP" to a Direction variable, the compiler will give an error and stop the program from running. This constraint helps catch mistakes early and keeps your program safe from invalid values. The execution steps show how the variable dir changes from uninitialized to NORTH, then EAST, and how invalid assignments are rejected.

Practice

(1/5)
1. Why do Kotlin enums constrain values to a fixed set?
easy
A. To prevent invalid values and reduce errors
B. To allow any value to be assigned
C. To make the code run faster
D. To increase the size of the program

Solution

  1. Step 1: Understand enum purpose

    Enums define a limited set of named values to represent options clearly.
  2. Step 2: Identify why limiting values helps

    Limiting values prevents invalid or unexpected inputs, reducing bugs.
  3. Final Answer:

    To prevent invalid values and reduce errors -> Option A
  4. Quick Check:

    Enums limit values = prevent errors [OK]
Hint: Enums fix allowed values to avoid mistakes [OK]
Common Mistakes:
  • Thinking enums allow any value
  • Believing enums improve speed directly
  • Confusing enums with variables
2. Which of the following is the correct syntax to declare an enum in Kotlin?
easy
A. enum Direction = { NORTH, SOUTH, EAST, WEST }
B. class enum Direction { NORTH, SOUTH, EAST, WEST }
C. enum class Direction { NORTH, SOUTH, EAST, WEST }
D. enum Direction { NORTH; SOUTH; EAST; WEST }

Solution

  1. Step 1: Recall Kotlin enum syntax

    Kotlin enums use 'enum class' followed by the name and curly braces with values separated by commas.
  2. Step 2: Check each option

    enum class Direction { NORTH, SOUTH, EAST, WEST } matches correct syntax; others have wrong keywords or separators.
  3. Final Answer:

    enum class Direction { NORTH, SOUTH, EAST, WEST } -> Option C
  4. Quick Check:

    Correct enum syntax = enum class Direction { NORTH, SOUTH, EAST, WEST } [OK]
Hint: Remember: 'enum class Name { VALUES }' [OK]
Common Mistakes:
  • Using 'class enum' instead of 'enum class'
  • Separating values with semicolons
  • Assigning enum like a variable
3. What will be the output of this Kotlin code?
enum class Color { RED, GREEN, BLUE }
fun main() {
    val c: Color = Color.GREEN
    println(c == Color.GREEN)
    println(c == Color.RED)
}
medium
A. false\nfalse
B. false\ntrue
C. true\ntrue
D. true\nfalse

Solution

  1. Step 1: Understand enum comparison

    Enum values are compared by identity. c is assigned Color.GREEN.
  2. Step 2: Evaluate println statements

    c == Color.GREEN is true; c == Color.RED is false.
  3. Final Answer:

    true\nfalse -> Option D
  4. Quick Check:

    Enum equality matches assigned value [OK]
Hint: Enum comparisons check exact named value [OK]
Common Mistakes:
  • Assuming enums compare by string content
  • Confusing true/false order
  • Using == incorrectly with enums
4. Identify the error in this Kotlin enum usage:
enum class Size { SMALL, MEDIUM, LARGE }
fun main() {
    val s: Size = Size.EXTRA_LARGE
    println(s)
}
medium
A. Cannot print enum values directly
B. Size.EXTRA_LARGE does not exist in the enum
C. Enum values must be lowercase
D. Missing semicolon after enum values

Solution

  1. Step 1: Check enum declaration

    Enum Size has only SMALL, MEDIUM, LARGE values defined.
  2. Step 2: Analyze usage error

    Code tries to assign Size.EXTRA_LARGE which is not defined, causing error.
  3. Final Answer:

    Size.EXTRA_LARGE does not exist in the enum -> Option B
  4. Quick Check:

    Using undefined enum value = error [OK]
Hint: Use only defined enum values [OK]
Common Mistakes:
  • Assuming enums accept any value
  • Thinking semicolons are required
  • Believing enum values must be lowercase
5. You want to restrict user input to only three modes: EASY, MEDIUM, HARD using Kotlin enums. Which approach best ensures invalid modes cannot be used in your program?
hard
A. Define enum class Mode { EASY, MEDIUM, HARD } and use Mode type for input
B. Use strings "EASY", "MEDIUM", "HARD" and check with if-else
C. Use integers 1, 2, 3 to represent modes without enum
D. Allow any string input and convert to uppercase

Solution

  1. Step 1: Understand enum benefits for input restriction

    Enums limit values to a fixed set, preventing invalid inputs.
  2. Step 2: Compare approaches

    Define enum class Mode { EASY, MEDIUM, HARD } and use Mode type for input uses enum type, ensuring only EASY, MEDIUM, HARD are valid. Others allow invalid inputs or require manual checks.
  3. Final Answer:

    Define enum class Mode { EASY, MEDIUM, HARD } and use Mode type for input -> Option A
  4. Quick Check:

    Enums enforce valid values automatically [OK]
Hint: Use enums to restrict allowed options [OK]
Common Mistakes:
  • Using strings without validation
  • Using integers without clear meaning
  • Allowing any input without checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard