Created
March 24, 2014 17:02
-
-
Save orionll/9744493 to your computer and use it in GitHub Desktop.
Pattern matching in Java via exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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