Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 504
Dónal Avatar asked Feb 03 '23 10:02

Dónal


2 Answers

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.

like image 169
Ruben Avatar answered Feb 05 '23 23:02

Ruben


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.

like image 20
Chad Gorshing Avatar answered Feb 06 '23 00:02

Chad Gorshing