Difference from Groovy: Modifying object reference within closure

8 views
Skip to first unread message

RonS

unread,
May 11, 2010, 9:34:09 AM5/11/10
to Groovy++
I'm just getting started with Groovy++ and came across this difference
between Groovy and Groovy++. Not sure if it's a bug so wanted to post
it here first:

@Typed
def f1(List rows) {
double fees = 0

rows.each { row ->
fees += row.fee
}
...
}

Yields the compile error:

Cannot modify final field com.rps.investrack.command.DisplayTradesCmd
$execute$1$1.fees
@ line 49, column 6.
fees += row.fee

If I change the type policy to DYNAMIC, no error.

Alex Tkachman

unread,
May 11, 2010, 11:27:48 AM5/11/10
to groovyp...@googlegroups.com
Yes, this is one of most significant differences with standard Groovy.
In Groovy++ shared closure variables are always final. I would rewrite
your code like

@Typed
def f1(List<Row> rows) {
double fees = 0

for(row in rows) {
fees += row.fee
}
...

Graeme Rocher

unread,
May 13, 2010, 1:28:37 PM5/13/10
to groovyp...@googlegroups.com
Seems a bit strange, is there no way to variables in groovy.lang.Reference statically? Would it be bad performance wise?

Cheers

Alex Tkachman

unread,
May 13, 2010, 2:00:22 PM5/13/10
to groovyp...@googlegroups.com
There are three philosofical reasons

1) it will be very bad performance wise. but if you really know what
you do you alway can use Reference directly. So the code can look like
this

def f1(List rows) {
Reference fees = 0d // compiler is smart enough will be Reference<Double>

rows.each { row ->
fees += row.fee
}
...
}

2) One of very often uses for closures is implementing "one method
abstract classes", which later will be send to different threads.
Mutable shared variable are too dangerous in this use cases

3) theoretically "closure" can be serialized and deserialized from
different JVM. in this case semantic of References is totally
undefined.

Because of all these three reasons we decided to be inconsistent with
normal Groovy in this area
Reply all
Reply to author
Forward
0 new messages