Groovy type conversion

casting, groovy, type-conversion

Solution

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.

Problem

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?

Original source