« Return to Thread: What happens to 'def' attributes in scripts?

Re: What happens to 'def' attributes in scripts?

by Jochen Theodorou :: Rate this Message:

Reply to Author | View in Thread

Niels B Nielsen schrieb:
> Great thanks,
>
> Just as I expected. That leads me to the following questions..

Edward was nearly right,

n=1
m=2
def add(another) {
   int x = n+another
   println "x is ${x}"
}
add(m)

becomes:

class Foo extends Script {
   def run() {
     n=1
     m=1
     add(m)
   }
   def add(another){
     int x = n+another
     println "x is $x"
   }
}


> 1) Why does methods have to be def'ed.
 > 2) How can I specify the type of my attribute?

def stands for a definition of either a method or variable. Types are
usually optional, but then Object is used. So your add methods takes an
Object parameter and returns an Object. Methods don't have to be def'ed,
you can also write for example:

long add(int a, long b){a+b}

> Some of the users have programming experience and
> a) either want def func() and def var to be consistent
> b) by mistake write int n=1 very often.

for grammar reasonssome kind of "introduction part" is needed. For
example this

static main(String[] args) {...}

does neither use def nor a type, still you define a method, because that
static is good enough for the compiler to recognize the definition. This
main method here will of course again return Object, for void, you have
to write void.

Does this answer your questions?

bye blackdrag

--
Jochen "blackdrag" Theodorou
The Groovy Project Tech Lead (http://groovy.codehaus.org)
http://blackdragsview.blogspot.com/


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


 « Return to Thread: What happens to 'def' attributes in scripts?