A question about implicit type conversion. See code sample below.
On line 3, an implicit conversion takes place by invoking the toString method
of the object.
On line 6, a similar construct, but with BigDecimal, fails with an exception:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot
cast object '10 kg' with class 'StockAmount ' to class 'java.math.BigDecimal'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast
object '10 kg' with class 'StockAmount' to class 'java.math.BigDecimal'
Why does toString() behave differently from toBigDecimal() ?
How can this be resolved?
Thanks,
Mike.
-----------------------------------------------------------------------------------------------
def sugarStock = new StockAmount(stockUnit:'kg', number:10)
String sAmount = sugarStock
assert sAmount == '10 kg'
BigDecimal bdAmount = sugarStock // Results in an exception
assert bdAmount == 10
class StockAmount {
BigDecimal number
String stockUnit
String toString() {
return "$number $stockUnit"
}
BigDecimal toBigDecimal() {
return this.number
}
}
-----------------------------------------------------------------------------------------------