Skip to content

Groovy With…

…surprises!

Following on from my earlier posting extolling the virtues of Groovy’s ‘with’ closure.

This bit me a while back…

Groovy’s Object.with(closure) method doesn’t constitute a ’scope’ and in fact global variables actually shadow the object instance ones.

Consider this script

// file: with.groovy
class X {
  def x
  def y
  def a
  def b
  }
  
static main(args) {
  def x = 99
  def y = 88
  new X(x: 42, y: 21, a: 0, b: 0).with {
    println "x: $x, y: $y, a: $a, b: $b"
    println "x: $it.x, y: $it.y, a: $it.a, b: $it.b"
    }
}

main(args)
// end with.groovy

Execution in GroovyConsole gives:

x: 99, y: 88, a: 0, b: 0
x: 42, y: 21, a: 0, b: 0

Note how on the first println $x is resolved to the global ‘x’, and so on.

It’s not really a bug…in hindsight it makes sense (as is the way with hindsight ;-)).

It is REALLY (UNpleasantly) surprising when one comes across this issue intially, however.

The tip for novice players is: always use the with closure’s parameter to access fields. Always.

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