Andrey Hihlovskiy

Professional blog on groovy, gradle, Java, Javascript and other stuff.

groovy: switch statement and closure comprehension – nice for DSL

It is rather easy to extend groovy switch statement with our own DSL:

def isGreaterThan(a, b) { a > b }

def isGreaterThan(b) {
  return { a -> isGreaterThan(a, b) }
}

def isLessThan(a, b) { a < b }

def isLessThan(b) {
  return { a -> isLessThan(a, b) }
}

def x = 5
def y = 6

switch(x) {
  case isGreaterThan(y):
    println "$x is greater than $y"
    break
  case isLessThan(y):
    println "$x is less than $y"
    break
  default:
    println "$x equals $y"
}

The trick here is that single-argument versions of IsGreaterThan, IsLessThan return closures. Switch-statement “understands” closures: it passes it’s argument (x in our case) as a parameter to the closure and expects boolean result being returned from the closure.Same thing can be done via function currying, but it looks not so nice, as with function overload.

By the way, DSL stands for “Domain Specific Language”. See more information here: http://en.wikipedia.org/wiki/Domain-specific_language

2 responses to “groovy: switch statement and closure comprehension – nice for DSL

  1. riic2000 September 4, 2013 at 13:47

    Hi ! I really like your blog ! Can you visited my blog and give a feedback or some sugestions ?
    1) http://gooprogrammer10.wordpress.com/
    2) http://riic2000.wordpress.com/

    Yesterday I created them and i don’t know how to make a good blog. I think I need some sugestions. Please help me telling your opinion.

    Thank you 🙂

  2. akhikhl September 4, 2013 at 14:55

    Hi Riic,
    I’m happy that you find my scribbles being useful.
    Regarding your question: yes, sure, why not.
    Two suggestions I could give immediately:
    1. Spelling and grammar should be improved. Using spellchecker would certainly help. The point is that we are blogging on quite complex matters; spelling and grammar errors should be reduced to minimum not to distract a reader from the content.
    2. When you describe trivia (like printf), it would be nice to refer to well-known textbooks (like “see more information in the book ‘The C++ Programming Language’ by Bjarne Stroustrup, ISBN 0-321-563840”). This way you gain more confidence from a reader or, at least, give him/her directions where to go further, if he/she is not satisfied with your description.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: