SyntaxHighlighter

Saturday, July 23, 2011

Dynamic type casting

Oh, I need to be careful with dynamic types in groovy.

If you do calculations on a BigDecimal with a Double (or double), you will get a Double back, not a BigDecimal.
Try the following in a groovyConsole to confirm.

import java.math.RoundingMode

def price = 10.25g
def tax = 1.1g
def afterTax = price * tax
println afterTax.getClass() // class java.math.BigDecimal
println afterTax.setScale(2, RoundingMode.HALF_UP) // 11.28

double tax_d = 1.1d
def afterTax_d = price * tax_d
println afterTax_d.getClass() // class java.lang.Double
println afterTax_d.setScale(2, RoundingMode.HALF_UP) // Will throw groovy.lang.MissingMethodException

No comments:

Post a Comment