Xelian
Xelian

Reputation: 17208

Boolean method in groovy always returns true

This code is a little bit stupid but it represents the problem fully. The two maps are different but true is allways returned. Why is this happening?

class SampleTest {

    private static boolean compare() {
        def a = [a:'one',b:'two']
        def b = [c:'three',d:'four']

        if(a.size()!=b.size()) {
            return false
        }
        a.each {
            if(!a.equals(b)){
                return false
            }
        }
        return true
    }
    static main(args) {
        println SampleTest.compare()
    }

}

If I add additional variable then all works fine:

class SampleTest {

    private static boolean compareArtifact() {
        boolean areEqual = true
        def a = [a:'one',b:'two']
        def b = [c:'three',d:'four']

        if(a.size()!=b.size()) {
            return false
        }
        a.each {
            if(!a.equals(b)){
                areEqual = false
            }
        }
        areEqual
    }
    static main(args) {
        println SampleTest.compareArtifact()
    }

}

Upvotes: 2

Views: 17236

Answers (1)

tim_yates
tim_yates

Reputation: 171084

You are calling return from inside a closure each

This will just exit the closure, but will not return from the enclosing function

You can use find as an early terminating loop, and check the result for null

private static boolean compare() {
    def a = [a:'one',b:'two']
    def b = [c:'three',d:'four']

    if( a.size() != b.size() ) {
        return false
    }
    return a.find { a != b } == null
}

Or return a == b does the same as your compare method

Upvotes: 7

Related Questions