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

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

by Martin C. Martin :: Rate this Message:

Reply to Author | View in Thread



Jochen Theodorou wrote:

> Niels B Nielsen schrieb:
>> Great thanks,
>>
>> Just as I expected. That leads me to the following questions..
>
>> 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}

To clarify a bit: "def" is only needed when the syntax is ambiguous.
Usually, that's when you don't specify a return type or any modifier.
So this is also valid (I think):

static add(a, b) { a+b }

I think your question is, "when I don't specify a type, why do I need
def for methods but not for script variables?"

An ambiguity comes with an expression like:

x = 23

If x hasn't been declared before, should this be the definition of a
local variable, or a setting a property on "this"?  Inside (explicit)
methods, we treat it as setting a property, and if you want the
definition, you need to add "def" (or return type, or modifier key word).

Scripts are different, the fact that you're defining a method (run) is a
kind of implementation detail.  We pretend its a kind of global scope,
so there's no property, so that a variable declaration is the best
interpretation.

Hope that helps,
Martin


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

    http://xircles.codehaus.org/manage_email


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