groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <dinko.sr...@gmail.com>
Subject Re: Confirming getProperties() works differently (inside vs outside)
Date Mon, 29 Feb 2016 09:30:45 GMT
I know this is not exactly what you asked, but would something like
this work for you?

    class Chameleon{ String color = "green" }

    trait ColorChanging {
        String lastColor
        def changeColor = {newcolor ->
            lastColor = this.color
            this.color = newcolor
        }
    }

    trait MyProps {
        void printAllMyProperties(){
            this.properties.each{println it}
        }
    }

    def mylizard = new Chameleon().withTraits(ColorChanging, MyProps)

    mylizard.changeColor('blue')

    mylizard.printAllMyProperties()
    mylizard.properties.each{println it}

Cheers,
Dinko

On 29 February 2016 at 03:23, Gerald Wiltse <jerrywiltse@gmail.com> wrote:
> Is there a way for the Chameleon class to ever see that it has a "lastColor"
> property?
>
> class Chameleon{
>     String color = "green"
>
>     void printAllMyProperties(){
>          this.properties.each{println it}
>     }
>
> }
>
> trait ColorChanging {
>     String lastColor
>     def changeColor = {newcolor ->
>         lastColor = this.color
>         this.color = newcolor
>     }
> }
>
> def mylizard = new Chameleon().withTraits(ColorChanging)
>
> mylizard.changeColor(blue)
>
> mylizard.printAllMyProperties()
> mylizard.properties.each{println it}
>
> The outputs of the two above lines don't match. lastColor isn't available
> from inside the class.
>
> This seems like it should be possible, but I tried several things including
> the declaredFields property and could not get the desired effect.
>
> In this script, I'm looking for a way for my instance to reference all the
> properties it's received from the trait. I guess it's same situation with
> inheritance, and properties added by propertymissing.
>
>
>
>
> Gerald R. Wiltse
> jerrywiltse@gmail.com
>

Mime
View raw message