groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paolo Di Tommaso <paolo.ditomm...@gmail.com>
Subject List and GString
Date Thu, 26 May 2016 18:06:30 GMT
Dear all,

I have a use case in which I need to override the `toString` method of a
custom List class and use it when interpolating that list object in a
GString.

It turns out the Groovy uses its own formatting methods for List and other
structures, so the my custom `toString` is simply ignored.

To explain it better take in consideration this example:

class MyList extends ArrayList {

  String toString() {
    this.join('-')
  }

}


def x = new MyList()
x << 1 << 2 << 3

assert x.toString() == '1-2-3'
assert "$x" == '1-2-3'

Assertion failed:
assert "$x" == '1-2-3'
         |  |
         |  false
         [1, 2, 3]

The second assertion fails for the reason said above. Now I'm wondering it
there's any way to override somehow the GString default rendering mechanism
in such a way I can inject my own formatting rule for my custom class.

Any suggestion is appreciated.



Cheers,
Paolo

Mime
View raw message