'Using instanceof in java 14 vs java 17 [duplicate]

My code runs in intellij on java 17 but returns an error on java 14 for the following line:

if (this.areas.get(i) instanceof Habitat area) {

which returns the error:

java: pattern matching in instanceof is a preview feature and is disabled by default.

How does one adjust this line so it works in java 14? I am aware the way I have used this feature only works in java 16+.



Solution 1:[1]

You have two options.

(1) You can enable the preview feature in Java 14, by compiling with

javac MainClass.java --enable-preview --release 14

and running with

java MainClass --enable-preview

(2) The line you wrote is equivalent to this.

if (this.areas.get(i) instanceof Habitat) {
    Habitat area = (Habitat) this.areas.get(i);

    // ... more here

Assuming, of course, that this get method doesn't have any nasty side-effects. This is how you do it if you don't want to enable the preview feature.

Solution 2:[2]

The old way is to test instanceof and them cast to the desired type:

if(this.areas.get(i) instanceof Habitat) {
  Habitat area = (Habitat) this.areas.get(i);
// rest of the if block

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dawood ibn Kareem
Solution 2 Sombriks