Return to site

โ˜• JAVA TRICK: Boolean expression in Pattern Matching

ยท java

You know pattern matching, but did you know that you can use the variable it introduces in the same boolean expression?

If you check whether the instance '๐จ๐›๐ฃ๐ž๐œ๐ญ' is of type '๐’๐ญ๐ซ๐ข๐ง๐ ' with '๐จ๐›๐ฃ๐ž๐œ๐ญ ๐ข๐ง๐ฌ๐ญ๐š๐ง๐œ๐ž๐จ๐Ÿ ๐’๐ญ๐ซ๐ข๐ง๐  ๐ฌ',

you can start using '๐ฌ' straight away, for example to check whether it's non-empty with '&& !๐ฌ.๐ข๐ฌ๐„๐ฆ๐ฉ๐ญ๐ฒ()'.

Object object = ...; // any object
if (object instanceof String s && !s.isEmpty()) {
  int length = s.length();
  System.out.println("This object is a non-empty string of length " + length);
} else {
  System.out.println("This object is not a string.");
}

This works in '๐ข๐Ÿ' statements in ๐‰๐š๐ฏ๐š ๐Ÿ๐Ÿ” and in '๐ฌ๐ฐ๐ข๐ญ๐œ๐ก' as a preview in ๐‰๐š๐ฏ๐š ๐Ÿ๐Ÿ•.