overloading the in operator in groovy

You can do stuff like this in Groovy:

def a = [1,2,3,4]
println 4 in a

and it will print true. I thought it would be cool to be able to do that for custom classes, but I didn’t know how to do it, so I asked on stackoverflow: question.
After I haven’t received an answer, I posted the same question on the groovy mailing list : nabble thread. Guillaume Laforge provided the solution: you need to override isCase.
Here’s something that works:

class Whatever {
   def container = []
   def addItem(item) {
      container << item
   def isCase(o) {
      return o in container

a = new Whatever()
println "two" in a

Really nice!


0 Responses to “overloading the in operator in groovy”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog Stats

  • 234,395 hits

%d bloggers like this: