groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Mario Garcia <mario.g...@gmail.com>
Subject Re: Custom implicit type conversion on assignment
Date Fri, 31 Mar 2017 22:41:53 GMT
Yes, the only "native" mechanism I know to do coertion in Groovy (without
applying metaprogramming) is to overwrite the asType method and apply it
explicitly.

For me creating an AST transform it's a very cool idea. Maybe, we could
come up with a library having a configuration file with predefined
coertions, like:

groovyx:
   coertions:
     Money:
       - BigDecimal: groovyx.coertions.money.BigDecimalToMoney //
BigDecimal -> Money using this implementation
       - String: groovyx.coertions.money.StringToMoney
       - Person: groovyx.coertions.money.StringToMoney

Cheers

On 31 Mar 2017 17:43, "Marcin Zajączkowski" <mszpak@wp.pl> wrote:

> Dnia Piątek, 31 Marca 2017 16:02 Marcin Zajączkowski <mszpak@wp.pl>
> napisał(a)
> > Hi,
> >
> > To simplify initialization of my production Money object in tests I've
> written an extension module to use explicit coercion:
> >
> > > Money tenDolars = 10.0 as Money     //works fine, but could be shorter
> >
> > It works fine, but it's Groovy so I would like to achieve more :).
> >
> > My idea is to be able to write:
> >
> > > Money tenDolars = 10.0      //desired construction
> >
> > I was thinking about AST transformation (global or annotation based) to
> modify assignments like those (with Money on the left side and BigDecimal
> on the right) in a given class (or globally in a test context) to add
> explicit coercion automatically.
> >
> > Unfortunately, usually AST transformations I've found deal with adding
> methods or statements in a method.
> >
> >
> > Could you point a Groovy build-in transformation or a place in Groovy
> code which deals with implicit coercion?
>
> Thanks to Groovy AST browser and debugger I was able to reach my goal for
> simple cases and in my AST transformation detect situations where right
> expression is ConstanstExpression with String type and replace it with
> CastExpression. Nevertheless, it seems to be very low level approach.
>
> Maybe it is possible to reuse some mechanisms available in Groovy to just
> extend existing coercion with new types?
>
> Marcin
>
> --
> http://blog.solidsoft.info/ - Working code is not enough
>
>
>
>

Mime
View raw message