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
asoperator 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
Objectinto aCarbecause we know that the object is instance ofCardeep down.But we cant do the following unless
Caris subclass ofBicyclewhich in fact does not make any sense (you will getClassCastExceptionin this case):asOperatorIn groovy to use the
asoperator the left hand operand must implement this method:As you can see the method accepts an instance of
Classand implements a custom converter so basically you can convertObjecttoCarorCartoBicycleif you want it all depends on your implementation.