Over a million developers have joined DZone.
Platinum Partner

Groovy Goodness: Append Values to Appendable Objects

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

Since Groovy 2.1 we have a couple of extra methods available for objects that implement the java.lang.Appendable interface. A lot of Writer objects implement this interface. The documentation of the Appendable interface mentions: An object to which char sequences and values can be appended.

First the leftShift() method is added. This means we can use the leftShift operator (<<) to append a value. Then we also can use the withFormatter() method. We can pass a closure to this method or a java.util.Locale object and a closure. The closure has a single parameter which is a java.util.Formatter instance. We can use this method to add printf-style formatted strings to an Appendable object. If we pass a Locale object to the method the Formatter is created with the specified Locale to created localized printf-sytle formatted strings.

// Create object that implements the Appendable interface.
final Appendable appendable = new StringWriter()

assert appendable in Appendable

// Use leftShift operator to add to Appendable implementation.
appendable << 'Groovy is Gr8!' << newLine

// Use withFormatter() method.
// Formatter object 
// is passed to closure as parameter.
appendable.withFormatter { formatter ->
    // Simple formatter pattern to reorder the arguments.
    formatter.format(/m r %3$1s %2$1s %1$1s %4$1s%n/, 'k', 'a', 'h', 'i')

// Use withFormatter() method and use Locale object
// as extra argument. The Locale is passed on
// to create the Formatter object.
appendable.withFormatter(Locale.US) { formatter ->
    formatter.format("US: " + datePattern, date)
// Use different Locale.
appendable.withFormatter(new Locale('nl')) { formatter ->
    formatter.format("Dutch: $datePattern", date)

// Check result is as expected:
assert appendable.toString() == '''Groovy is Gr8!
m r h a k i
US: January 27, 2013
Dutch: januari 27, 2013

// Helper getters:

String getNewLine() {

Date getDate() {
    // Simple date to use in withFormatter() methods.
    Date.parse('yyyy-MM-dd', '2013-01-27')

String getDatePattern() {
    // Date pattern for Formatter.
    '%1$tB %1$te, %1$tY%n'

Code written with Groovy 2.1


The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}