Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 46 Next »

Groovy uses both " and ' for strings. Either can be used. Using either type of string allows you to use strings with quotations easily.

The groovy parser supports the notation \uab12 (i.e. a leading backslash and precisely four hex digits after the 'u' ).
This notation can be used in strings or anywhere in the program like the Java parser does.

Concatenation

Strings may be concatenated with "+". For example:

Multi-line strings

Regular strings in Groovy cannot span multiple lines.

As an exception to this rule, a backslash at the end of a line disappears and joins the current line with the next.

If you have a block of text which you wish to use but don't want to have to encode it all (e.g. if its a block of HTML or something) then you can use the """ syntax.


Because of the leading backslash, the string text contains exactly two newlines. There are always represented by the character '\n', regardless of the line-termination conventions of the host system.

It is also possible to use triple single quotes for multi-line strings, but they are not GStrings, so interpolating variables doesn't work in that case.

Slashy String literals

It is possible to use the another notation for String literals with the added benefit of not needing additional backslashes to escape special characters. That is especially handy with regular expressions or Windows file/directory path names.

The only escape that is supported in a slashy string is to use \/ to embed a slash into the string (Unicode characters (\uxxxx) are parsed before getting to the different String representations.). A consequence of this is that you can't have a backslash as the last character of a slashy string directly (or Groovy will think you are trying to escape the closing string terminator - and hence won't think you have terminated your string). Instead use: def bs = '\\\\'; def winpath=/C:\windows\system32$bs/ or def winpath=/C:\windows\system32\${}/.

Another gotcha: don't try using an empty slashy string: def x = //, the slashes will be treated as a line comment delimiter, but def z = /${}/ would be fine.

A final gotcha: currently a slashy string can't be the left hand side (LHS) expression of an assert statement while you are eliminating the brackets, e.g.:

This is a feature of the current grammar rather than a desired goal and may one day be altered to remove this anomoly - it is a tricky edge case in the grammar.

Examples

Icon

For more examples, read about Regular Expressions.

Strings are immutable

This can be seen with these two code snips, which you can cut and paste into groovyConsole:

Above both variables are references to the map.
If you do the same thing with Strings, the behavior is different:

Here, sn and st point at the very same map object in memory in the first example, while in the second snippet, at the end, st points at a  different place in memory where there's the new immutable string.

GStrings

Strings that are declared inside double-quotes (i.e. either single double-quotes or triple double-quotes for multi-line strings) can contain arbitrary expressions inside them as shown above using the ${expression} syntax in a similar way to JSP EL, Velocity and Jexl. Any valid Groovy expression can be enclosed in the ${...} including method calls etc. GStrings are defined the same way as normal Strings would be created in Java. Here is a simple example involving a simple variable and an expression:

What actually happens is whenever a string expression contains a ${...} expression then rather than a normal java.lang.String instance, a GString object is created which contains the text and values used inside the String.

GString can involve lazy evaluation so it's not until the toString() method is invoked that the GString is evaluated. This lazy evaluation is useful for things like logging as it allows the calculation of the string, the calls to toString() on the values, and the concatenation of the different strings to be done lazily if at all. Here is an example that illustrates lazy evaluation:

which outputs the following:

Thu Apr 17 23:18:17 EST 2008
It is currently Thu Apr 17 23:18:17 EST 2008
It is currently Thu Apr 17 23:18:22 EST 2008

To explain this output, we need to understand additional rules about GStrings. Each value in the GString (where $ appears) is the result of an expression. Most often, the expression is evaluated resulting in an Object, as in all the examples above except for the case of the variable y in which the expression is a Closure.

Only when the GString is converted into a String (as for println) is the expression's result converted and incorporated into the result String. Each of the values to be substituted into the GString is obtained by applying one of the following methods:

  • General Object instances are converted by the toString() method; there is special handling for types like array, Stream, Collection, etc.
  • Closure instances taking 0 parameters are called and the returned value is converted to String by the same rules as for a general Object (a returned Closure will not be called).
  • Closure instances taking 1 parameter are called with a Writer as the parameter; characters written to the Writer become part of the String result. The return from the Closure is ignored.
  • Closure instances taking more than 1 parameter are not called; the GString throws GroovyRuntimeException.

So, in the example above, x contains an instance of Date resulting from new Date() being invoked at the time x was assigned. When we print x later, that calculated value is placed in the appropriate place in the GString and output giving us the date at GString definition time. The other GString, y, contains a 1 parameter closure which means that the closure will be stored away in the GString. When we print out y, the closure will be invoked and give the date at printing time.

GStrings aren't Strings

Icon

GString and String are two distinct classes, and hence use of GString objects as keys for Map objects or comparisons involving GString objects, can produce unexpected results when combined with String objects since a GString and a String won't have the same hashCode nor will they be equal. There is no automatic coercion between the two types for comparisons or map keys, so it's sometimes necessary to explicitly invoke toString() on GString objects.

On the other hand GStrings can easily be made into Strings

Unexpected conversion to String can lead to problems when code is expecting a GString, as for methods in groovy.sql classes. That's a case were explicit types can be beneficial:

GString Use Cases - Templating

GString is pretty handy when you don't want to use a template engine, or when you really want full lazy evaluation of GStrings. When some variable embedded in a GString, the toString() is called on that variable to get a string representation, and it's inserted into the final string. But when it's closures you embed, we don't call the toString() on closure. If that was the case, you'd get a string like "Script7$_run_closure1@8dc50e" embedded in your final string.

Instead, we distinguish two use cases:

  1. a closure with no parameter, i.e.
    { -> }
  2. a closure with one parameter.

And the expected behaviors:

  • For a closure with no parameter, Groovy calls the closure without parameter, and calls toString() on the result.
  • For a closure with one parameter, the parameter is actually a StringWriter to which you can append text in the body of your closure.
  • For a closure with more parameters, an exception will be thrown.

Illustration:

Result:

I'm executed
Executed with a class java.io.StringWriter parameter
no param - one param

The embedded closure could be used in a nested manner:

result:

how deep is deep? deeper and deepest
how deep is deep? deeper and deepest

GString Use Cases - GSQL

Another use case for GString is GSQL where parameters can be passed into SQL statements using this same mechanism which makes for a neat way to integrate Groovy with other languages like SQL. GroovySql then converts the expressions to ? and uses a JDBC PreparedStatement and passes the values in, preserving their types.

If you explicitly want to coerce the GString to a String you can use the toString() method. Groovy can also automatically coerce GStrings into Strings for you.

String and StringBuffer Methods

See: JN1525-Strings.

More Examples

The following example passes the test:

and outputs:

item: "bread"
item: "apple"
item: "egg"

  • No labels