4

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+.

kusama
  • 69
  • 1
  • 5
  • 2
    As another user pointed out, this is described at https://stackoverflow.com/q/61939967/, which tells you how to use Java 14 with this feature enabled. If you don't want to enable the feature, you have to declare `area` and do a cast. – Dawood ibn Kareem Apr 05 '22 at 20:54

2 Answers2

7

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
3

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
Sombriks
  • 3,370
  • 4
  • 34
  • 54