Created
November 23, 2022 20:41
-
-
Save enikao/57bb1b10ce3126494ec4baa2bc7db2df to your computer and use it in GitHub Desktop.
Java Combining assert statement and instanceof pattern matching
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 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