Skip to content

Instantly share code, notes, and snippets.

@sgalles
Created November 15, 2013 22:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgalles/7492937 to your computer and use it in GitHub Desktop.
Save sgalles/7492937 to your computer and use it in GitHub Desktop.
Something I've always wanted to do in Java : union of enums. Here, applied to a simple use case : exhaustive (checked by compiler) i18n of an app, with keys coming from different enums.
// enum 1 of application i18n keys
abstract class AppKeyi18n()
of title | description {}
object title extends AppKeyi18n() {}
object description extends AppKeyi18n() {}
// enum 2 of user i18n keys
abstract class UserKeyi18n()
of fieldText1 | fieldText2 | fieldText3 {}
object fieldText1 extends UserKeyi18n() {}
object fieldText2 extends UserKeyi18n() {}
object fieldText3 extends UserKeyi18n() {}
// union of enums
alias AllKeyi18n => AppKeyi18n|UserKeyi18n;
// french translation of all keys
String translateFrench(AllKeyi18n key) {
switch (key) // exhaustive switch
case (title) { return "frtitle"; }
case (description) { return "frdescr"; }
case (fieldText1) { return "frtext1"; }
case (fieldText2) { return "frtext2"; }
case (fieldText3) { return "frtext3"; }
}
// english translation of all keys
String translateEnglish(AllKeyi18n key) {
switch (key) // exhaustive switch
case (title) { return "entitle"; }
case (description) { return "endescr"; }
case (fieldText1) { return "entext1"; }
case (fieldText2) { return "entext2"; }
case (fieldText3) { return "entext3"; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment