Is there any practical difference between the following two approaches to casting:
result.count = (int) response['hits']['total']
vs
result.count = response['hits']['total'] as int
I'm using @CompileStatic
and the compiler is wanting me to do the cast - which got me wondering if there was any performance or practical difference between the two notations.
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
E.g:
As we can see on the example we are casting an object of class
Object
into aCar
because we know that the object is instance ofCar
deep down.But we cant do the following unless
Car
is subclass ofBicycle
which in fact does not make any sense (you will getClassCastException
in this case):as
OperatorIn groovy to use the
as
operator the left hand operand must implement this method:As you can see the method accepts an instance of
Class
and implements a custom converter so basically you can convertObject
toCar
orCar
toBicycle
if you want it all depends on your implementation.