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 ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.