‘in’ the groove

I’m sure most of you are aware of the standard Groovy for loop:

for (i in 0..<10) {
    ...
}

It can also iterate over lists:

for (name in listOfNames) {
    ...
}

For many people, that’s where the story of in ends. But did you know that it can be used in conditions as well? Try this:

assert 5 in 0..<10
assert 5 in 0..5
assert !(5 in 0..<5)
assert 5 in [ 1, 4, 5, 7, 8 ]
assert !(5 in [ 1, 2, 4, 7, 8 ])

So it works for ranges and lists. Of course, it also works for sets. And not just numbers, but all objects (because they implement equals()). So if you have code like so

names.findAll { it.firstName == "Peter" || it.firstName == "Alan" }

you can make it a bit more Groovy by using in:

names.findAll { it.firstName in [ "Peter", "Alan"] }

Wonderful stuff. One last note: beware using it with BigDecimal floating point numbers because it may not work the way you expect:

def numbers = [ 1.0, 2.00, 4.567, 3.123 ]
assert 1.0 in numbers
assert 1.000 in numbers

The second assertion fails because 1.0 != 1.000 according to BigDecimal.equals(). Of course, that may change in a future version of Groovy, so it’s always worth checking out in the Groovy console or shell first.

Have fun with your new friend!

6 thoughts on “‘in’ the groove

  1. Dierk König

    Cool post!
    One should mention that ‘in’ is based on the isCase() method and is thus available for _any_ object and adaptable to ones needs.
    if (x in Float)
    if (x in ~/regex/)
    etc.

    see also Groovy in Action, second edition.

  2. Peter Post author

    Thanks for the correction and clarification Dierk. I have to say, this is one instance where Groovy doesn’t do what I would expect it to. This works as you say:

    def x = 1.0F
    assert x in Float

    but doesn’t make much sense to my eyes, whereas this doesn’t work:

    def x = “st”
    assert x in “string”

    but I would expect it to. The BigDecimal behaviour is another anomaly.

  3. Steve

    Sounds like “in” should sometimes be “is” … or perhaps “instanceof”?

    Definitely come confusion around this point — but generally a very cool feature.

Leave a Reply

Your email address will not be published. Required fields are marked *