Search code examples
javainstanceofjava-17

Java Pattern Variable Scope


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
    }
}

Solution

  • 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”.