Pergunta

I can't override grails getter method and becoming crazy.

What I want is use a double value and a string value to get a formatted data, but when I'm typing my override method into String, the double value is null and when into double, it obviously get me an error because a String is returned !

I get a domain class like that :

class Project {
    ...
    String currency
    Double initialTargetAmount
        ...
}

First Override method (initialTargetAmount is null in this case) :

//@Override Comment or uncomment it does not make any change to the behaviour
public String getInitialTargetAmount() {
        println "${initialTargetAmount} ${currency}" // display "null EUR"
        "${initialTargetAmount} ${currency}" // initialTargetAmount is null
}

Second method :

//@Override Comment or uncomment it does not make any change to the behaviour
public Double getInitialTargetAmount() {
        println "${initialTargetAmount} ${currency}" // display "1000.00 EUR"
        "${initialTargetAmount} ${currency}" // Error : String given, Double expected
}

Any help is welcome.

Snite

Foi útil?

Solução

Groovy has dynamic getters and setters.

So, initalTargetAmount field "creates" automatically a Double getInitialTargetAmount method. Which is why it works when you have the Double return Type. But when you set String, getInitialTargetAmount automatically refers to a field String initalTargetAmount which doesn't exist

Try changing the name of the method, for example getInitialAmountWithCurrency() and it will work. Maybe your best bet will be to override toString() method ^^

Outras dicas

Your getter should be always the same type of your field, and it's noot a good approach to change the getter like this, because Grails (Hibernate internally) will understand that your object instance changed and will try to update it ( it will check the old and new values).

You're trying in fact is to have a String representation of your amount, so you have a couple of options to this:

1 - A new method

Creating a new method that returns String will not interfere in the hibernate flow and you can use it anywere.

class Project {
    ...
    String currency
    Double initialTargetAmount
    ...
    String displayTargetAmount() {
       "${initialTargetAmount} ${currency}"
    }

}

2 - TagLib

Depending on your needs, you could create a TagLib to make this custom representations of your class. This can include html formatting.

class ProjectTagLib {
  static namespace = "proj"

  def displayAmount = { attrs ->
    if(!attrs.project) {
      throwTagErrro("Attribute project must be defined.")
    }

    Project project = attrs.remove('project')
    //just an example of html
    out << "<p>${project.initialTargetAmount} , ${project.currency}</p>" 

  }

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top