variable declaration syntax: use cases and thoughts

We discussed this at the GC1 (Groovy Conference#1) and we used the
token 'def' to represent variable/field declarations.
Firstly in Java variable declarations are always different to
assignments as a type is mandatory. So we're already used in the Java
world to explicit variable declarations. The issue for groovy is, if
the type is optional, there's no difference between them from a syntax
perspective, which causes some issues...
1. Catching common typos
foot = 1
if (bar) foo = 2 // the user mistyped the variable name
print foot
2. Declarations without value assignment
Since we're hoping to use the no-dumb-expression handling to catch
types and bad newlines, statements such as the following are bad
x
+x
So we can't just define variables with 1 token. We need a declaration
token (or to disallow variable declarations without a value - i.e. use
regular assigment x = 1).
e.g.
class Foo {
x
}
is a bit wierd; our mental grammar models makes this feel wrong. So
with a variable/field declaration token this feels better
class Foo {
x = 1
}
or
class Foo {
var x
}
It must be said that in interactive shells, folks are used to typing
things like
x = 123
and not having to make explicit variable declarations; so I think the
requirement for variable declaration syntax is mostly for defining
fields and variables inside method bodies.
There's been much debate over def / any / let / var etc. Many people
have been plain confused by 'any' which despite its simplicity, I'm now
thinking we should avoid - we probably just need a token associated
with declaring a field/variable. I'm currently liking something from
JavaScript - using 'var' is my current favourite.
someMethod() {
var foot = 123
if (bar) {
foo = 4 // BAD compile error unknown variable
}
return foot
}
Then using 'def' for defining methods/functions.
Coming from Java, the use of 'var' (or any new token) is a little
strange at first; but then we're used to typing some token anyways in
Java for declarations.
I've grappled with this issue for some time and I'm now pretty
convinced we need some simple token for those wishing to define a
variable with no static type; so far I'm now leaning towards 'var'.
Thoughts?
James
-------
http://radio.weblogs.com/0112098/