1

I cannot understand why my simple String equality test is returning false.

Code is:

boolean isDevelopment() {
        //config.project_stage is set to "Development"
        String cfgvar = "${config.project_stage}" 
        String comp = "Development"
        assert cfgvar.equals(comp)
    }

Result is:

assert cfgvar.equals(comp)
       |      |      |
       |      false  Development
       Development 

I also get false if I do:

assert cfgvar == comp

3 Answers 3

6

toString() is not necessary. Most probably you have some trailing spaces in config.project_stage, so they are retained also in cfgvar.

comp has no extra spaces, what can be seen from your code.

Initially the expression "${config.project_stage}" is of GString type, but since you assign it to a variable typed as String, it is coerced just to String, so toString() will not change anything.

It is up to you whether you use equals(...) or ==. Actually Groovy silently translates the second form to the first.

So, to sum up, you can write assert cfgvar.trim() == comp.

You can also trim cfgvar at the very beginning, writing:

cfgvar = "${config.project_stage}".trim()

and then not to worry about any trailing spaces.

Sign up to request clarification or add additional context in comments.

1 Comment

nice summary. Thanks Valdi!
3

Have you checked for trailing spaces? At least your output as one for the first Development. Try a .trim() when you compare those strings (and maybe a .toLowerCase() too)

And remember: .equals() in Groovy is a pointer comparison. What want to do is ==. Yes, just the opposite from what it is defined in Java, but the Groovy definition makes more sense :-)

Update: see comment by @tim_yates - I mixed .equals() up with .is()

2 Comments

equals is not a pointer comparison in Groovy... You're thinking of is()
This one did work rtn = cfgvar.toString().trim() == comp. I'm so happy!!! Thanks rdmueller :-). It may not be syntactically perfect but after struggling for 2 hours with it I don't care. I have a deadline. Thanks again for the quick help!!!
1

On of the objects you comparing is not a String but GString, try:

cfgvar.toString().equals(comp)

However your code works with groovy v. 2.4.5. Which version are you using?

3 Comments

I am using version 2.4.5. but cfgvar.toString().equals(comp) also returns false.
Afaik it is not a GString - just a variable replacement. GString would be "${-> something}" , wouldn't it?
@rdmueller it would not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.