groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Emmanuel Rosa <goaway1...@gmail.com>
Subject Re: List and GString
Date Thu, 26 May 2016 21:02:04 GMT
The rendering is actually produced by InvokerHelper: https://github.com/apache/groovy/blob/master/src/main/org/codehaus/groovy/runtime/InvokerHelper.java#L123
<https://github.com/apache/groovy/blob/master/src/main/org/codehaus/groovy/runtime/InvokerHelper.java#L123>

I tried overriding it with a category and also via the metaClass, but neither worked. I recall
some kind of trick that’s needed when using the metaClass with some classes, to get it to
take, but I don’t remember the details. :(

> On May 26, 2016, at 2:06 PM, Paolo Di Tommaso <paolo.ditommaso@gmail.com> wrote:
> 
> 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