logo

Polyglot CheatSheet - enum

Last Updated: 2022-04-04

C++

According to Google C++ Style Guide, enumerators should be named like constants (like kOutOfMemory) instead of macros (OUT_OF_MEMORY ) to avoid conflicts.

enum class Color {
  kRed = 0,
  kBlue,
  kOrange,
};

Java

enum DayOfWeek {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Java's enum is more like a class, it can have constructor and methods:

class Test {
  enum DayOfWeek {
    SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    private final int num;

    // constructor
    DayOfWeek(int num) {
      this.num = num;
    }

    // method
    public boolean isWeekDay() {
      return this != SUNDAY && this != SATURDAY;
      // or: return num >= 1 && num <= 5;
    }
  }

  public static void main(String[] args) {
    System.out.println(DayOfWeek.FRIDAY.isWeekDay()); // => true
    System.out.println(DayOfWeek.SUNDAY.isWeekDay()); // => false
  }
}

ProtoBuf

enum Corpus {
  UNIVERSAL = 0;
  WEB = 1;
  IMAGES = 2;
  LOCAL = 3;
  NEWS = 4;
  PRODUCTS = 5;
  VIDEO = 6;
}