Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting In Groovy

Tags:

groovy

I have two questions.

I did the following code to find the ASCII value of $ :

def a = "\$"
def b = (int)a 
println b //prints 36

Well I'm happy with the answer. But when I tried to do it in reverse like this, I found I'm missing something :

def a = 36
String b = a
println b // getting output only 36 

Question 1:

So my first question is why it prints 36 and why not $? Am I wrong here?

Well if the same first code block is re-written as:

    def a = "\$"
    def b = a as int
    println b

If I run this program I get an error like this :

Caught: java.lang.NumberFormatException: For input string: "$"
    at T.run(T.groovy:2)

Even though I'm trying to do the same as before. I'm getting an error.

Question 2:

So why does the as keyword doesn't work here and does def a = (int)b is not equal to to def a = b as int? Explain me.

Thanks in advance.

like image 753
Ant's Avatar asked Oct 01 '11 09:10

Ant's


People also ask

What is toString Groovy?

Groovy - toString()The method is used to get a String object representing the value of the Number Object. If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.

What are the data types in Groovy?

Groovy supports the same primitive types as defined by the Java Language Specification: integral types: byte (8 bit), short (16 bit), int (32 bit) and long (64 bit) floating-point types: float (32 bit) and double (64 bit) the boolean type (one of true or false )

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]


1 Answers

when you cast a string to int it's ok while you have one char in it, so we can say you cast a char to int, when you try to cast int to a string i think it uses toString method or something like that. Try to cast 36 to char and you'll see your '$'

like image 132
wiero Avatar answered Sep 28 '22 08:09

wiero