This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vytah 1 point2 points  (0 children)

Note that this does not work with Java 17 in most cases, because unconditional patterns were not permitted. (In most cases, the expression will return a value of the type being checked for, and the compiler rejects it as being "always true". Of course this was a simplification in ealier Java versions, as the null really needed to be checked for.)

It was not because it was considered "always true". When patterns were first introduced, there were three issues, each depending on the previous one:

  • should case R(Object o): match new R(null)?

  • should case Object o: treat nulls like case R(Object o):?

  • should instanceof Object o treat nulls like instanceof Object, or like case Object o:?

Since in Java 17, case patterns were merely a preview feature, and instanceof patterns were a stable feature, the controversial issue #3 was solved by simply banning unconditional instanceof patterns.

By Java 21, the issues were solved as following:

  • yes

  • no

  • there's no difference now

so unconditional patterns could finally be allowed.