views:

778

answers:

3

Hi,

In Groovy you can do surprising type conversions using either the as operator or the asType method. Examples include

Short s = new Integer(6) as Short
List collection = new HashSet().asType(List)

I'm surprised that I can convert from an Integer to a Short and from a Set to a List, because there is no "is a" relationship between these types, although they do share a common ancestor.

For example, the following code is equivalent to the Integer/Short example in terms of the relationship between the types involved in the conversion

class Parent {}
class Child1 extends Parent {}
Class Child2 extends Parent {}

def c = new Child1() as Child2

But of course this example fails. What exactly are the type conversion rules behind the as operator and the asType method?

+1  A: 

I believe the default asType behaviour can be found in: org.codehaus.groovy.runtime.DefaultGroovyMethods.java and org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.java.

Starting from the DefaultGroovyMethods it is quite easy to follow the behaviour of asType for a specific Object type and requested type combination.

Ruben
A: 

According to what Ruben has already pointed out the end result of:

Set collection = new HashSet().asType(List)

is

Set collection = new ArrayList( new HashSet() )

The asType method recognizes you are wanting a List and being the fact HashSet is a Collection, it just uses ArrayList's constructor which takes a Collection.

As for the numbers one, it converts the Integer into a Number, then calls the shortValue method.

I didn't realize there was so much logic in converting references/values like this, my sincere gratitude to Ruben for pointing out the source, I'll be making quite a few blog posts over this topic.

Chad Gorshing
A: 

The GroovyMag issues from May 2009 till now contain a series of articles on Groovy typing and type conversion.

Ruben