Last active
December 22, 2021 09:03
-
-
Save nbness2/94e1bcb0ae65768913934d375f3a8ab4 to your computer and use it in GitHub Desktop.
Example of pattern matching in java
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 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