Groovy Strings

Groovy adds a new string known as a GString. A GString can be created by declaring a literal with double quotes; a string literal with single quotes is a java.lang.String. A GString can be used in place of a Java String. If a method is expecting a String and is given a GString, it will be cast at runtime.

The beauty and power of the GString is its ability to evaluate embedded Groovy expressions. Groovy expressions can be designated in two ways. For simple values that are not directly adjacent to any plain text, you can just use a dollar sign, like this:

 
"Hello ​$name​"

For more involved expressions, you can use the dollar sign and a pair of curly braces:

 
"The 5th letter in 'Encyclopedia' is ​${​'Encyclopedia'​[4]}​

Get Grails 2: A Quick-Start Guide 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.