Skip to content

Instantly share code, notes, and snippets.

@enikao
Created November 23, 2022 20:41
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 enikao/57bb1b10ce3126494ec4baa2bc7db2df to your computer and use it in GitHub Desktop.
Save enikao/57bb1b10ce3126494ec4baa2bc7db2df to your computer and use it in GitHub Desktop.
Java Combining assert statement and instanceof pattern matching
public class AssertPatternMatching {
public static void main(String[] args) {
Object obj = args.length == 0 ? Integer.valueOf(42) : "Hello";
afterAssert(obj);
insideMessage(obj);
}
private static void afterAssert(Object obj) {
assert obj instanceof String str;
str.length();
}
private static void insideMessage(Object obj) {
assert !(obj instanceof String str) : "Is a string: " + str.length();
obj.hashCode();
}
private static void afterAssertIf(Object obj) {
if(obj instanceof String str) {
str.length();
} else {
throw new AssertionError();
}
}
private static void insideMessageIf(Object obj) {
if (!(obj instanceof String str)) {
obj.hashCode();
} else {
throw new AssertionError("Is a string: "+ str.length());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment