The main difference is that casting uses the concept of inheritance for conversion, where the as operator is a custom converter that may or may not use the concept of inheritance.
Which one is faster?
It depends on the implementation of the converter method.
Casting
Well, all castings actually mean taking an object of one particular type and "turning it into" another type of object. This process is called variable casting.
For instance:
Object object = new Car(); Car car = (Car)object;
As we see in the example, we throw an object of class Object into Car , because we know that the object is an instance of Car in depth.
But we cannot do this if Car not a subclass of Bicycle , which actually makes no sense (in this case, you will get a ClassCastException ):
Object object = new Car(); Bicycle bicycle = (Bicycle)object;
as Operator
In Groovy, we can override the asType () method to convert an object to another type. We can use the asType () method in our code to call the conversion, but we can even make it shorter and use it like that.
In Groovy, to use the as operator, the left operand must implement this method:
Object asType(Class clazz) {
As you can see, the method accepts an instance of Class and implements its own converter, so you can convert Object to Car or Car to Bicycle if you want all this to depend on your implementation.
source share