Sunday, February 28, 2021

Using binding variable in the expression of if statement

Yes. We can use the binding variable inside of an if expression as long as its assured that when the code flow reaches that expression its assured that the instanceof operator has evaluated to true

Below sample code illustrates this


interface Pet {
    default public String color() {
        return this.color();
    }
}

record Dog(String color) implements Pet {

    public void bark() {
        System.out.println("I bark...");
    }
}

record Cat(String color) implements Pet {

    public void meaw() {
        System.out.println("I meaw...");
    }
}

public class Main {

    public static void main(String[] args) {

        Pet p1 = new Dog("White");
        Pet p2 = new Cat("White");

        if (p1 instanceof Dog d && d.color().equals("White") && 
                p2 instanceof Cat c && c.color().equals("White")) {
            d.bark();
            c.meaw();
        }
    }
}

Here we are using the binding variables c & d inside of an if expression. Note that the usage is allowed when used with short-circuit && operator, which makes sure the subsequent expression gets evaluated only when the 1st condition evaluates to true. 


Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Instanceof-Binding-Variable/In-if-expression

No comments:

Post a Comment