Steeven_b
Steeven_b

Reputation: 777

Groovy Cast primitive type

I want to set fields dynamically in groovy so I have a java code that get datas from a database and I set groovy fields using Bindings.setVariable() in java.

I would like to know if it is possible to cast each primitive types in groovy. String to int, String to float and so on. So I could always send a string and cast in an other primitive times, it depends of the type of my groovy fields.

Upvotes: 0

Views: 1259

Answers (2)

bdkosher
bdkosher

Reputation: 5883

@Opal's as solution is good, but I also wanted to mention that the Groovy JDK adds some convenient primitive check and conversion methods to CharSequence, which String implements:

  • isDouble and asDobule
  • isFloat and asFloat
  • isLong and asLong
  • isInteger and asInteger

Interestingly, it isFloat seems to be greedy, returning true for floating points beyond its range.

['2', '2.2', '2' * 10, "${Double.MAX_VALUE}"].each { s ->
    switch (s) {
        case { it.isInteger() }:
            int i = s.toInteger()
            println "String '$s' -> int $i"
            break  
        case { it.isLong() }:
            long l = s.toLong()
            println "String '$s' -> long $l"
            break
        case { it.isFloat() }:
            float f = s.toFloat()
            println "String '$s' -> float $f"
            break             
        case { it.isDouble() }:
            double d = s.toDouble()
            println "String '$s' -> double $d"
            break     
        default:
            println "$s is not a supported primitive"
    }
}

prints out

String '2' -> int 2
String '2.2' -> float 2.2
String '2222222222' -> long 2222222222
String '1.7976931348623157E308' -> float Infinity

Upvotes: 4

Opal
Opal

Reputation: 84766

It depends on what you exactly need, but the following piece of code works well:

assert '2' as Integer == 2
assert '2.2' as Double == 2.2

Upvotes: 2

Related Questions