Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - as vs (cast)

Tags:

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.

like image 404
Kong Avatar asked Apr 16 '17 23:04

Kong


People also ask

What is as in Groovy?

We can change the type of objects with the as keyword in Groovy. We can even make maps and closure look like interface implementations when we use as . Furthermore we can use as to create an alias for an import statement. 1.

Is Groovy slower than Java?

"With the @CompileStatic, the performance of Groovy is about 1-2 times slower than Java, and without Groovy, it's about 3-5 times slower.

What does ==~ mean in Groovy?

In Groovy, the ==~ operator is "Regex match". Examples would be: "1234" ==~ /\d+/ -> evaluates to true. "nonumbers" ==~ /\d+/ -> evaluates to false.


1 Answers

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.

like image 65
dsharew Avatar answered Oct 08 '22 00:10

dsharew