lqdev
lqdev

Reputation: 403

How to get a property from a trait implementation in Groovy?

I have a trait, called MyTrait.

package properties

trait MyTrait {
    abstract String property

    String getThatProperty() {
        "$property is that property"
    }
}

Then I have a class implementing the trait.

package properties

class PropertiesTesting implements MyTrait {
    String property = 'Hello'
}

The problem is, when I go and call PropertiesTesting#getThatProperty(), it returns "null is that property". How can I fix that so it returns "x is that property" with x varying depending on the implementation? I do not want to rewrite code for each class that implements the trait.

Upvotes: 1

Views: 1288

Answers (3)

MaterialZ
MaterialZ

Reputation: 351

It takes the trait's property (which is null) instead of the class's property. Comment out the trait's String property and add a println command if you want to print the sentence.

package properties

trait MyTrait {
    //abstract String property

    String getThatProperty() {
        println "$property is that property"
    }
}
class PropertiesTesting implements MyTrait {
    String property = 'Hello'
}
def instance = new PropertiesTesting()
instance.getThatProperty()

Upvotes: 0

Szymon Stepniak
Szymon Stepniak

Reputation: 42204

I would disagree that encapsulating state in a trait is a good choice. Even though it might seen like something that is possible to do, it carries the same problems as extending classes with their state.

Solution to your problem is even simpler - let your trait defines abstract String getProperty() method instead. Something like this:

trait MyTrait {
  abstract String getProperty()

  String getThatProperty() {
    "$property is that property"
  }
}

class PropertiesTesting implements MyTrait {
  String property = 'Hello'
}

def properties = new PropertiesTesting()

assert properties.getThatProperty() == 'Hello is that property'

Adding a field property in PropertiesTesting adds a proper getProperty() method and when you call getThatProperty() method for the trait is uses getProperty() from PropertiesTesting class. It's easier and more straightforward.

Upvotes: 4

lqdev
lqdev

Reputation: 403

The answer is to simply use object.properties.

To get the property property of PropertiesTesting, I can use instance.properties['property'].

Upvotes: 0

Related Questions