juan
juan

Reputation: 81902

Is there any difference between declaring a variable with 'def' and declaring it with a known type?

Assuming I have a defined class

class MyClass {
}

Is there a hit in performance in runtime in doing def c = new MyClass() instead of MyClass c = new MyClass()? Or is it exactly the same?

Upvotes: 2

Views: 289

Answers (1)

Arturo Herrero
Arturo Herrero

Reputation: 13122

def is a replacement for a type name. In variable definitions it is used to indicate that you don't care about the type.

If you don't declare the type of variable, Groovy under the covers will be declared as type Object. You can think of def as an alias of Object.

In your example:

def c = new MyClass()
// transform to:
java.lang.Object c = new MyClass()

MyClass c = new MyClass()
// transform to:
MyClass c = new MyClass()

Upvotes: 3

Related Questions