tags:

views:

79

answers:

2

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 ( http://stackoverflow.com/questions/3935832/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!

+5  A: 

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.

ammoQ
my original hope was that def performaed that way but when I tried something such as: 'def DOB = new Date(1999,5,2); dob.getYear();' it wont let me build
Without Me It Just Aweso
and then the runtime exceptions flowed...
hvgotcodes
I just tried your example of .toUppercase and that also wont allow me to build.. am I missing a compiler setting or something? I'm using netbeans 6.9.1
Without Me It Just Aweso
Have you created your project as a groovy project?!?
ammoQ
And of course, to build something, you have to declare a class, just like in Java. It's just that the groovy console lets you enter and execute statements directly, but that's not a build.
ammoQ
+3  A: 

You can experiment with groovy in the groovy web console http://groovyconsole.appspot.com/

Your initial groovy date example works.

Przemyslaw