O'Reilly logo

Programming Groovy 2 by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

GString Lazy-Evaluation Problem

The result we get from GString expressions depends on whether we use values or references in the expression. The result may lead to some surprises if we’re not careful how we compose the expression. Learning this now will help avoid stumbling like your humble author did when learning about string manipulation in Groovy. Here’s the example that worked well in the previous section:

WorkingWithStrings/LazyEval.groovy
 
what = ​new​ ​StringBuilder​(​'fence'​)
 
text = ​"The cow jumped over the ​$what​"
 
println text
 
 
what.replace(0, 5, ​"moon"​)
 
println text

The output from the code looks pretty reasonable:

 
The cow jumped over the fence
 
The cow jumped over the moon

The GString (text) contains the variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required