Groovy - as vs (cast)
Asked Answered
B

1

28

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.

Bolanos answered 16/4, 2017 at 23:45 Comment(0)
R
27

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.

Rachelrachele answered 17/4, 2017 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.