Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Groovy def and Java Object?

Tags:

java

groovy

I'm trying to figure out the difference between

Groovy:

def name = "stephanie"

Java:

Object name = "stephanie"

as both seem to act as objects in that to interact with them i have to cast them to their original intended type.

I was originally on a search for a java equivalent of C#'s dynamic class ( Java equivalent to C# dynamic class type? ) and it was suggested to look at Groovy's def

for example my impression of groovy's def is that I could do the following:

def DOB = new Date(1998,5,23);
int x = DOB.getYear();

however this wont build

thanks,steph

Solution edit: Turns out the mistake iw as making is I had a groovy class wtih public properties (in my example above DOB) defined with def but then was attemping to access them from a .java class(in my example above calling .getYear() on it). Its a rookie mistake but the problem is once the object leaves a Groovy file it is simply treated as a Object. Thanks for all your help!

like image 616
Without Me It Just Aweso Avatar asked Oct 14 '10 20:10

Without Me It Just Aweso


People also ask

What is the difference between Groovy and Java?

Groovy can be used as both programming and scripting Language. Groovy is a superset of Java which means Java program will run in Groovy environment but vice-versa may or may not be possible. Whereas Java is strongly and statically typed programming language.

What does def mean in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

Should I use def in Groovy?

Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation. The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable.

How do you define an object in Groovy?

A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class.


1 Answers

Per se, there is not much difference between those two statements; but since Groovy is a dynamic language, you can write

def name = "Stephanie"
println name.toUpperCase() // no cast required

while you would need an explicit cast in the Java version

Object name = "Stephanie";
System.out.println(((String) name).toUpperCase());

For that reason, def makes much more sense in Groovy than unfounded use of Object in Java.

like image 186
Erich Kitzmueller Avatar answered Oct 13 '22 05:10

Erich Kitzmueller