Skip to content

Instantly share code, notes, and snippets.

@jharrilim
Created July 16, 2022 19:50
Show Gist options
  • Save jharrilim/9739997bf5a0b74100aefe14e5301bac to your computer and use it in GitHub Desktop.
Save jharrilim/9739997bf5a0b74100aefe14e5301bac to your computer and use it in GitHub Desktop.
Java developer: Mom can we have pattern matching? Mom: We have pattern matching at home
public class Main {
public static void main(String[] args) {
try {
Parser.parse("yo");
} catch (StringType s) {
System.out.println(s.value);
} catch (IntegerType i) {
System.out.println(i.asString());
} catch (Type _t) {
System.out.println("unknown type");
}
}
}
class Parser {
static void parse(Object o) throws Type {
if (o instanceof String) throw new StringType((String)o);
if (o instanceof Integer) throw new IntegerType((int)o);
}
}
class Type extends Exception { }
class StringType extends Type {
public final String value;
public StringType(final String value) {
this.value = value;
}
}
class IntegerType extends Type {
private final int value;
public String asString() {
return String.valueOf(value);
}
public IntegerType(final int value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment