Enums — cheat sheet
From: fundamentals/13-enums.md.
- What: a fixed, predetermined set of values, defined as its own type (
enum Direction { NORTH, EAST, SOUTH, WEST }) — usable anywhere any other type is. - Why not just Strings/ints for this: those allow any value, not just the intended handful — nothing stops a typo'd string or an out-of-range number from compiling.
- The core benefit — type safety: comparing/switching on enum constants means the compiler rejects references to values that don't exist. Concretely: if a diagonal direction (
NORTH_EAST, etc.) is later removed from the enum because it's no longer supported, every leftovercase Direction.NORTH_EASTordirection == Direction.NORTH_EASTin the codebase fails to compile — turning a silent dead-code bug (which happens with plainString/.equals()checks, where old branches just quietly stop being reached) into a compiler error that forces cleanup. - Comparison: use
==between enum constants (safe, since each constant is a singleton instance) rather than.equals(). - Fields on an enum: an enum constant can carry its own data via a constructor, just like a regular class — e.g. a
Directionenum storing a human-readablenamefield, withtoString()overridden to return it. switchon enums: works likeswitchonString/int(case VALUE:per constant,break,default), but gets the same type-safety guarantee as==.