Skip to content

The Old (Groovy) Switch-eroo Again…

Recently, I had the little task of looking at a string and deciding what to do based on the various values of an embedded prefix field.

I had to ask around a bit (thanks Paul!) to get the solution to my liking, but here’s yet another example of my favourite Groovy construct, the switch statement:

def days = [
  "Monday:I could wait till Tuesday",
  "Tuesday:must make up my mind",
  "Wednesday:would be fine",
  "Thursday:she's on my mind",
  "Friday:give me time",
  "Saturday:I could wait",
  "Sunday:would be too late"
]

final MON = 'Monday:'
final TUE = 'Tuesday:'
final WED = 'Wednesday:'
final THU = 'Thursday:'
final FRI = 'Friday:'
final SAT = 'Saturday:'
final SUN = 'Sunday:'

days.each { value ->
  switch(value) {
    case ~/^${MON}.*$/:
      println "$MON: ${value - MON}"
      break
    case ~/^${TUE}.*$/:
      println "$TUE: ${value - TUE}"
      break
    case ~/^${WED}.*$/:
      println "$WED: ${value - WED}"
      break
    case ~/^${THU}.*$/:
      println "$THU: ${value - THU}"
      break
    case ~/^${FRI}.*$/:
      println "$FRI: ${value - FRI}"
      break
    case ~/^${SAT}.*$/:
      println "$SAT: ${value - SAT}"
      break
    case ~/^${SUN}.*$/:
      println "$SUN: ${value - SUN}"
      break
  }
}

I know it’s a very contrived example, but take a look at the case ‘labels’: regular expressions that reference properties found elsewhere in the code. Neat-o!

Apologies to Sting (did you get the song?)!

Tags: ,

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB