Skip to content

Instantly share code, notes, and snippets.

@nbness2
Last active December 22, 2021 09:03
Show Gist options
  • Save nbness2/94e1bcb0ae65768913934d375f3a8ab4 to your computer and use it in GitHub Desktop.
Save nbness2/94e1bcb0ae65768913934d375f3a8ab4 to your computer and use it in GitHub Desktop.
Example of pattern matching in java
public interface Animal {
String getName();
String getNoise();
default String makeNoise() { return getName() + " made a noise: " + getNoise(); }
}
public static void useThing(Object thing) {
if (thing instanceof Animal animalThing) {
System.out.println("thing is an animal!! what kind?? " + animalThing.getName());
System.out.println(animalThing.makeNoise());
} else if (thing instanceof Integer intThing) {
System.out.println("thing is an Integer! if you added 3 to it you would have: " + (intThing + 3));
} else {
System.out.println("i don't really know what that is...");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment