groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srkoč <dinko.sr...@gmail.com>
Subject Re: Implicit type conversion
Date Tue, 26 Jan 2016 08:57:13 GMT
On 24 January 2016 at 17:29, Mike M mike_m_@outlook.com
<http://mailto:mike_m_@outlook.com> wrote:

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() ?

Method toString() exists in the Object class, and Object is at
the top of the inheritance hierarchy. This means the method can be
used whenever an object needs a string representation. On the other
hand, there is no concept of “BigDecimal representation of an object”.

All this comes from Java.

How can this be resolved?

What you could do is override asType(Class) method and use the as operator
(
http://docs.groovy-lang.org/docs/latest/html/documentation/#_coercion_operator
):

import org.codehaus.groovy.runtime.typehandling.GroovyCastException
def sugarStock = new StockAmount(stockUnit:'kg', number:10)

String sAmount = sugarStock as Stringassert sAmount == '10 kg'

BigDecimal bdAmount = sugarStock as BigDecimal // this is now OKassert
bdAmount == 10
class StockAmount {
    BigDecimal number
    String stockUnit
    String toString() { "$number $stockUnit" }
    BigDecimal toBigDecimal() { this.number }

    def asType(Class target) {
        switch(target) {
            case String:     return toString()
            case BigDecimal: return toBigDecimal()            default:
throw new GroovyCastException(
                "I'm sorry Dave, I'm afraid I can't do that")
        }
    }
}

Cheers,
Dinko

>

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