views:

150

answers:

2

Hi,

Groovy supports a literal syntax for creating a StringBuilder/StringBuffer instead of the usual

def sb = new StringBuilder()

However, I can't seem to remember (or find on Google) the correct syntax.

Thanks, Don

+2  A: 

To create a StringBuilder

text = 'Hello '

To append

text <<= 'World!'

And this might help some more.

omerkudat
It seems that that text is converted from a String to a StringBuilder only when the '<<=' operator is used, correct?Also, it's actually a StringBuffer not a StringBuilder
Don
Yes, in fact my example might be overly simplistic. You do need to convert and reassign to StringBuffer, as such the `<<=` operator. Later you can just use `<<`. Also you are right about the `StringBuffer`, which is how they allowed in-place character replacement using the `[]` operator.
omerkudat
+2  A: 

To get a StringBuffer in a single step, you could use

def sb = 'Hello'<<''

or even:

def sb = ''<<'' //4 single quotes, not double quotes

for an initially empty one.

I think (but I could be wrong) the reason for using a StringBuffer rather than a StringBuilder is to maintain compatibility with Java 1.4.

matt