Skip to content
Skip to breadcrumbs
Skip to header menu
Skip to action menu
Skip to quick search
Quick Search
Browse
Pages
Blog
Labels
Attachments
Mail
Advanced
What’s New
Space Directory
Feed Builder
Keyboard Shortcuts
Confluence Gadgets
Log In
Dashboard
Groovy
Copy Page
You are not logged in. Any changes you make will be marked as
anonymous
. You may want to
Log In
if you already have an account. You can also
Sign Up
for a new account.
This page is being edited by
.
Paragraph
Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Preformatted
Quote
Bold
Italic
Underline
More colours
Strikethrough
Subscript
Superscript
Monospace
Clear Formatting
Bullet list
Numbered list
Outdent
Indent
Align left
Align center
Align right
Link
Table
Insert
Insert Content
Image
Link
Attachment
Symbol
Emoticon
Wiki Markup
Horizontal rule
tinymce.confluence.insert_menu.macro_desc
Info
JIRA Issue
Status
Gallery
Tasklist
Table of Contents
Other Macros
Page Layout
No Layout
Two column (simple)
Two column (simple, left sidebar)
Two column (simple, right sidebar)
Three column (simple)
Two column
Two column (left sidebar)
Two column (right sidebar)
Three column
Three column (left and right sidebars)
Undo
Redo
Find/Replace
Keyboard Shortcuts Help
<p>Groovy uses both " and ' for strings. Either can be used. Using either type of string allows you to use strings with quotations easily.</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> println "he said 'cheese' once" println 'he said "cheese!" again' </pre></td></tr></table> <p>The groovy parser supports the notation \uab12 (i.e. a leading backslash and precisely four hex digits after the 'u' ).<br /> This notation can be used in strings or anywhere in the program like the Java parser does.</p> <h2>Concatenation</h2> <p>Strings may be concatenated with "+". For example: <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> #!/usr/bin/env groovy a = "world" print "hello " + a + "\n" </pre></td></tr></table> <h2>Multi-line strings</h2> <p>Regular strings in Groovy cannot span multiple lines.</p> <p>As an exception to this rule, a backslash at the end of a line disappears and joins the current line with the next. <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> // this is a compile error def foo = "hello </pre></td></tr></table> <p>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. <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def name = "James" def text = """\ hello there ${name} how are you today? """ assert text != null println(text) </pre></td></tr></table> <p><br class="atl-forced-newline" /> Because of the leading backslash, the string <code>text</code> contains exactly two newlines. There are always represented by the character <code>'\n'</code>, regardless of the line-termination conventions of the host system.</p> <p>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.</p> <h2>Slashy String literals</h2> <p>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.</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def s = /.*foo.*/ def dirname = /^.*\// def basename = /[Strings and GString^\/]+$/ </pre></td></tr></table> <p>The only escape that is supported in a slashy string is to use <code>\/</code> to embed a slash into the string. 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: <code>def bs = '\\\\'; def winpath=/C:\windows\system32$bs/</code> or <code>def winpath=/C:\windows\system32\${}/</code>.</p> <p>Another gotcha: don't try using an empty slashy string: <code>def x = //</code>, the slashes will be treated as a line comment delimiter, but <code>def z = /${}/</code> would be fine.</p> <p>A final gotcha: currently a slashy string can't be the left hand side (LHS) expression of an <code>assert</code> statement while you are eliminating the brackets, e.g.:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> assert 'ab' == 'a' + 'b' // OK, no slashy string assert 'a' + 'b' == /ab/ // OK, slashy string on RHS assert (/ab/ == 'a' + 'b') // brackets currently required if slashy string is on LHS </pre></td></tr></table> <p>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.</p> <table class="wysiwyg-macro" data-macro-name="tip" data-macro-parameters="title=Examples" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e3RpcDp0aXRsZT1FeGFtcGxlc30&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="RICH_TEXT"><tr><td class="wysiwyg-macro-body"> <p>For more examples, read about <a class="confluence-link" href="/display/GROOVY/Regular+Expressions" data-linked-resource-id="2768" data-linked-resource-type="page" data-linked-resource-default-alias="Regular Expressions" data-base-url="http://docs.codehaus.org">Regular Expressions</a>.</p></td></tr></table> <h2>Strings are immutable</h2> <p>This can be seen with these two code snips, which you can cut and paste into groovyConsole: <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> st = ["status":"test"] sn = st println sn st.status = "tset" println sn </pre></td></tr></table> <p>Above both variables are references to the map.<br /> If you do the same thing with Strings, the behavior is different: <br class="atl-forced-newline" /></p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> st = "test" sn = st println sn st = "tset" println sn </pre></td></tr></table> <p>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. <br class="atl-forced-newline" /></p> <h2>GStrings</h2> <p>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 <em>${expression}</em> 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:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> foxtype = 'quick' foxcolor = ['b', 'r', 'o', 'w', 'n'] println "The $foxtype ${foxcolor.join()} fox" // => The quick brown fox </pre></td></tr></table> <p>What actually happens is whenever a string expression contains a ${...} expression then rather than a normal java.lang.String instance, a <a href="http://groovy.codehaus.org/api/groovy/lang/GString.html">GString</a> object is created which contains the text and values used inside the String.</p> <p>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:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> println new Date() x = "It is currently ${ new Date() }" assert x.values[0] instanceof Date y = "It is currently ${ writer -> writer << new Date() }" assert y.values[0] instanceof Closure sleep 5000 println x println y </pre></td></tr></table> <p>which outputs the following:</p> <table class="wysiwyg-macro" data-macro-name="noformat" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e25vZm9ybWF0fQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> 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 </pre></td></tr></table> <p>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 <code>y</code> in which the expression is a Closure.</p> <p>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:</p> <ul> <li>General Object instances are converted by the toString() method; there is special handling for types like array, Stream, Collection, etc.</li> <li>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).</li> <li>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.</li> <li>Closure instances taking more than 1 parameter are not called; the GString throws GroovyRuntimeException.</li> </ul> <p>So, in the example above, <code>x</code> contains an instance of Date resulting from <code>new Date()</code> being invoked at the time <code>x</code> was assigned. When we print <code>x</code> 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, <code>y</code>, 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.</p> <table class="wysiwyg-macro" data-macro-name="warning" data-macro-parameters="title=GStrings aren't Strings" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e3dhcm5pbmc6dGl0bGU9R1N0cmluZ3MgYXJlbid0IFN0cmluZ3N9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="RICH_TEXT"><tr><td class="wysiwyg-macro-body"> <p>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.</p> <p>On the other hand GStrings can easily be made into Strings</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def s = "String " def g = "GString created at ${new Date()}" def x = s + g assert s instanceof String assert g instanceof GString assert x instanceof String </pre></td></tr></table> <p>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:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def s = "String " def g = "GString created at ${new Date()}" GString x = GString.EMPTY + s + g assert s instanceof String assert g instanceof GString assert x instanceof GString println x </pre></td></tr></table></td></tr></table> <h3>GString Use Cases - Templating</h3> <p>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.</p> <p>Instead, we distinguish two use cases:</p> <ol> <li>a closure with no parameter, i.e.<br /> { -> }</li> <li>a closure with one parameter.</li> </ol> <p>And the expected behaviors:</p> <ul> <li>For a closure with no parameter, Groovy calls the closure without parameter, and calls toString() on the result.</li> <li>For a closure with one parameter, the parameter is actually a StringWriter to which you can append text in the body of your closure.</li> <li>For a closure with more parameters, an exception will be thrown.</li> </ul> <p>Illustration:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def noParam = { -> println "I'm executed"; return "no param" } def oneParam = { out -> println "Executed with a ${out.class} parameter"; out << "one param" } assert noParam.toString() != "no param" println "${noParam} - ${oneParam}" </pre></td></tr></table> <p>Result:</p> <table class="wysiwyg-macro" data-macro-name="noformat" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e25vZm9ybWF0fQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> I'm executed Executed with a class java.io.StringWriter parameter no param - one param </pre></td></tr></table> <p>The embedded closure could be used in a nested manner:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> def deepest = {-> "deepest"} def deep = {-> "deeper and $deepest"} println "how deep is deep? $deep" // which is equivalent to: println "how deep is deep? ${{-> "deeper and ${{-> "deepest"}}"}}" // for demonstrating it is a nested usage only </pre></td></tr></table> <p>result:</p> <table class="wysiwyg-macro" data-macro-name="noformat" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e25vZm9ybWF0fQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> how deep is deep? deeper and deepest how deep is deep? deeper and deepest </pre></td></tr></table> <h3>GString Use Cases - GSQL</h3> <p>Another use case for GString is <a class="confluence-link" href="/display/GROOVY/GSQL" data-linked-resource-id="17023" data-linked-resource-type="page" data-linked-resource-default-alias="GSQL" data-base-url="http://docs.codehaus.org">GSQL</a> 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.</p> <p>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.</p> <h2>String and StringBuffer Methods</h2> <p>See: <a class="confluence-link" href="/display/GROOVY/JN1525-Strings" data-linked-resource-id="77561" data-linked-resource-type="page" data-linked-resource-default-alias="JN1525-Strings" data-base-url="http://docs.codehaus.org">JN1525-Strings</a>.</p> <h2>More Examples</h2> <p>The following example passes the test:</p> <table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> aaa = '"bread","apple","egg"' items = aaa.split(',') assert items[1] == '"apple"' items.each{ println "item: $it" } </pre></td></tr></table> <p>and outputs:</p> <p>item: "bread"<br /> item: "apple"<br /> item: "egg"</p>
Please type the word appearing in the picture.
Attachments
Labels
Location
Watch this page
< Edit
Preview >
Loading…
Save
Cancel
Next hint
search
attachments
weblink
advanced