A search for meaning in software and life
RSS icon Email icon Home icon
  • ‘in’ the groove

    Posted on January 14th, 2010 Peter 6 comments

    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!