ajwang / groovypptest

Automatically exported from code.google.com/p/groovypptest
0 stars 0 forks source link

recursive closure calls give null pointers #313

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
In Groovy++ v.0.2.24, c in this example gives a null pointer, but in dynamic 
Groovy 1.7.5 (without @Typed), the code works correctly.

@Typed package test
Closure c
c= {int i->
  if(i < 5) c(i + 1) //c ref'd here gives NullPointer
  else 9
}
println c(0)

I know I can use call() function for this particular example, but I've other 
more complicated code where I need to pass the reference around correctly.

Original issue reported on code.google.com by gavingro...@gmail.com on 13 Nov 2010 at 1:51

GoogleCodeExporter commented 8 years ago
You need explicitly define 'c' as
Reference<Closure> c
c = { ... }

Original comment by alex.tka...@gmail.com on 13 Nov 2010 at 4:37

GoogleCodeExporter commented 8 years ago
Running your code as quoted gives:
  Cannot convert { int -> ...} to Reference<Closure>

Running this also gives the null pointer error in Groovy++, but not in Groovy:
  @Typed package test
  import java.lang.ref.*
  SoftReference<Closure> rc
  Closure c= {int i->
    if(i < 5) rc.get()(i + 1)
    else 9
  }
  rc= new SoftReference<Closure>(c)
  println c(0)

Original comment by gavingro...@gmail.com on 13 Nov 2010 at 11:50

GoogleCodeExporter commented 8 years ago
Just to close the Reference<Closure> suggestion by Alex, if it is of any help, 
here is the way through the Reference<Closure> / recursive closure call maze:

----------------------------------------------
@Typed package test

Closure c
Reference<Closure> rc = []

c = {int i ->
    if(i < 5) 
        rc.get()(i + 1)
    else 
        9
}

rc.set(c)
assert c(0) == 9
----------------------------------------------

Original comment by roshanda...@gmail.com on 2 Jan 2011 at 9:40

GoogleCodeExporter commented 8 years ago
Thanks, Roshan. Only just noticed your comment, which solves my immediate 
problem. When I read Alex's comment, I used java.lang.ref.Reference instead of 
groovy.lang.Reference, hence that problem.

Not sure if you want to keep this issue open or not. My initially reported code 
sample works in Groovy 1.7.5 but not Groovy++ 4.116. Perhaps it never can 
because of the statically-typed nature of Groovy++. I'll leave it to you 
whether to close or not.

Original comment by gavingro...@gmail.com on 18 Jan 2011 at 8:57