Reputation: 3696
Basically this happens
def map = [a:"Hello", b: "World", c: true, d: false]
println("a" in map) // true
println("b" in map) // true
println("c" in map) // true
println("d" in map) // false WHY????
Upvotes: 2
Views: 179
Reputation: 407
The in
operator, or rather the Membership Operator is represented by the isCase
method, which was originally added for switch
statements.
I can't tell you why they decided to implement it this way, but it is implemented like this for Maps:
org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(java.util.Map, java.lang.Object)
/**
* 'Case' implementation for maps which tests the groovy truth
* value obtained using the 'switch' operand as key.
* For example:
* <pre class="groovyTestCase">switch( 'foo' ) {
* case [foo:true, bar:false]:
* assert true
* break
* default:
* assert false
* }</pre>
*
* @param caseValue the case value
* @param switchValue the switch value
* @return the groovy truth value from caseValue corresponding to the switchValue key
* @since 1.7.6
*/
public static boolean isCase(Map caseValue, Object switchValue) {
return DefaultTypeTransformation.castToBoolean(caseValue.get(switchValue));
}
If you want to be certain to check only the keys you need to write something like this x in map.keys()
.
Upvotes: 3