Groovy literal StringBuilder/StringBuffer

Dónal picture Dónal · Nov 25, 2009 · Viewed 32.3k times · Source

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.

Answer

matt picture matt · Nov 25, 2009

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.