Skip to content

Instantly share code, notes, and snippets.

@orionll
Created March 24, 2014 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orionll/9744493 to your computer and use it in GitHub Desktop.
Save orionll/9744493 to your computer and use it in GitHub Desktop.
Pattern matching in Java via exceptions
public class Main {
public static void main(String[] args) {
System.out.println(example());
}
public static String example() {
try {
throw match();
} catch (Int x) {
return "This is an integer. Its value is " + x.value;
} catch (Str str) {
return "This is a string. Its value is " + str.value;
}
}
public static Matchable match() {
throw new Int(5);
}
}
class Matchable extends Error {
}
class Int extends Matchable {
final int value;
Int(int value) {
this.value = value;
}
}
class Str extends Matchable {
final String value;
Str(String value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment