groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Mike M <mike...@outlook.com>
Subject Implicit type conversion
Date Sun, 24 Jan 2016 16:29:01 GMT
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
  }
}

-----------------------------------------------------------------------------------------------



Mime
View raw message