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?