Dónal
Dónal

Reputation: 187529

Groovy type conversion

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?

Upvotes: 10

Views: 15904

Answers (2)

Ruben
Ruben

Reputation: 9120

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

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

Upvotes: 8

Chad Gorshing
Chad Gorshing

Reputation: 3118

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.

Upvotes: 5

Related Questions