Search code examples
groovyinstanceof

Why is Groovy not catching my instanceof?


In the following code:

static void main(String[] args) {
    String str

    if(str instanceof String) {
        println "'str' is a String!"
    } else {
        println "I have absolutely no idea what 'str' is."
    }
}

The statement "I have absolutely no idea what 'str' is." is what prints. Why, and what can I do to make Groovy see that str is a String (besides making the String non-null)?


Solution

  • Because str is null, which is not a String.

    The instanceof keyword interrogates the object that the reference points to, not the reference type.

    EDIT

    Try this...

    static void main(args) {
        String str = 'King Crimson Rocks!'
    
        if(str instanceof String) {
            println "'str' is a String!"
        } else {
            println "I have absolutely no idea what 'str' is."
        }
    }