-
‘in’ the groove
Posted on January 14th, 2010 6 commentsI’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 responses to “‘in’ the groove”
-
Thanks Peter! You are right when you say “For many people…”… now there’s one less person!
Gotta love it! -
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.
-
This is great! I never thought about using “in” in a findAll – thanks for posting!
-
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 Floatbut 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.
-
well, it only makes sense when considering the isCase() heritage.
“in” does _not_ denote a containment but a classification! -
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
-





Social Media