CHAPTER 12

Enum

Enum provides a very simple functionality - a set of named constants.

Define an enum with a couple of constants:

  enum Planet {
    Venus,
    Earth,
    Mars
  }

Enum type is checked during assignment and function call. For compiled language, this is one advantage over numbers. Unfortunately this type checking can only happen during runtime in Julian.

  void explore(Planet p) {
  
  }
  
  Planet pl = Planet.Earth;
  explore(pl);

There are two fields built into an enum value: an ordinal value in integer and a name in string. When declaring the enum, ordinal values can be overwritten. If not, it starts from 0 and increments by one for each constant.

  enum Planet {
    Venus = 10,
    Earth,
    Mars = 30
  }
  
  Console.println(Planet.Venus.ordinal); // 20
  Console.println(Planet.Earth.ordinal); // 21
  Console.println(Planet.Mars.ordinal); // 30
  
  Console.println(Planet.Venus.name); // Venus

When declaring a new Enum variable without an initializer, the first constant will be assigned to it. However, it's still possible to assign a null value to enum.

  enum Planet {
    Venus,
    Earth,
    Mars
  }
  
  Planet p;
  Console.println(Planet.Venus.ordinal); // 0
  Console.println(Planet.Venus.name); // Venus

Last but not least, enum can be switched on.

  Planet pl = ...;
  switch(pl){
  case Planet.Venus: ...; break;
  case Planet.Earth: ...; break;
  default: break;
  }

Enum is essentially a special class type, with its constants implemented as static members of the same type, each containing two fields.