Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 383
IAmYourFaja Avatar asked Dec 01 '14 21:12

IAmYourFaja


1 Answers

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."
    }
}
like image 171
Jeff Scott Brown Avatar answered Sep 23 '22 08:09

Jeff Scott Brown