The main difference is casting uses the concept of inheritance to do the conversion where the as
operator is a custom converter that might or might not use the concepts of inheritance.
Which one is faster?
It depends on the converter method implementation.
Casting
Well, all casting really means is taking an Object of one particular
type and “turning it into” another Object type. This process is called
casting a variable.
E.g:
Object object = new Car();
Car car = (Car)object;
As we can see on the example we are casting an object of class Object
into a Car
because we know that the object is instance of Car
deep down.
But we cant do the following unless Car
is subclass of Bicycle
which in fact does not make any sense (you will get ClassCastException
in this case):
Object object = new Car();
Bicycle bicycle = (Bicycle)object;
as
Operator
In Groovy we can override the method asType() to convert an object
into another type. We can use the method asType() in our code to
invoke the conversion, but we can even make it shorter and use as.
In groovy to use the as
operator the left hand operand must implement this method:
Object asType(Class clazz) {
//code here
}
As you can see the method accepts an instance of Class
and implements a custom converter so basically you can convert Object
to Car
or Car
to Bicycle
if you want it all depends on your implementation.