Home > other >  Java Pattern Variable Scope
Java Pattern Variable Scope

Time:09-17

I am going through Oracle's official docs to understand Pattern Variable scope in Java 17. In the following example, the method testScope1 works as explained in the docs, but the method testScope2 gives a compilation error. I am not able to figure out why void return type of the method is causing the issue?

interface Vehicle{}
class Car implements Vehicle{}

class Pattern{
    public int testScope1(Vehicle v){
        if(!(v instanceof Car c)){
            return 1;
        }
        System.out.println(c.toString());  //WORKS FINE
        return 2; 
    }
    public void testScope2(Vehicle v){
        if(!(v instanceof Car c)){
                 
        }
        System.out.println(c.toString());  //COMPILE TIME ERROR: Cannot resolve symbol c
    }
}

CodePudding user response:

Think about what happens if v is not a Car instance:

  • In testScope1, the return 1; statement causes the method to be exited. No subsequent statements of the method are exceuted. All is well.
  • In testScope2 there’s no return, so the control flow reaches c.toString(). But v isn’t a Car, so … what is c?! It can’t exist, because it would have to be of type Car but that’s a counterfactual. That’s why you’re getting the error “Cannot resolve symbol c”.

CodePudding user response:

Put an else statement. Pattern variable will be created only if instanceof operator yields true. Otherwise there is no variable, and hence the compiler error.

  public void testScope2(Vehicle v){
      if(!(v instanceof Car c)){
             
      } else {
        System.out.println(c.toString());
      }
  }

Edit: testScope1 method does not need else statement because the return statement is already there. return statement is ensuring that control never reaches c.toString() if v is not an instance of Car.

CodePudding user response:

Having spent more thoughts on this I have an explanation: The variable can only be accessed if the instanceof is clearly true for that piece of code.

In testScope1 you cannot access c within the if statement. But since the code after the if statement only gets executed when the instanceof is true, c is accessible.

In testScope1 you cannot access c within the if statement. But since the code after the if statement gets executed regardless of instanceof being true or false c is not accessible. After all we might have the false situation and the compiler acts accordingly.

  • Related