Groovy literal StringBuilder/StringBuffer

groovy, stringbuilder

Solution

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.

Problem

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.

Original source

Related problems