2
votes

In the Groovy console, version 2.2.1: Why does this work?

class C {
  def foo = { "foo" }
  def bar = { foo() }
}
new C().bar()

but this fails?

class C {
  String foo = { "foo" }
  String bar = { foo() }
}    
new C().bar()

The above was answered by tim_yates but I have something somewhat related that doesn't seem like it's worth creating a new question for (not sure of the etiquette). When I make them static it also fails when I call bar(). Why does the bar closure not capture foo?

class C {
  static foo = { "foo" }
  static bar = { foo() }
}    
C.foo() //works
C.bar() //fails
1
I think that should be a different question - tim_yates
Thanks, tim_yates. I posted it here - jrk

1 Answers

3
votes

Because neither { "foo" } or { foo() } are Strings?

They are Closure<String>

Try:

class C {
  Closure<String> foo = { "foo" }
  Closure<String> bar = { foo() }
}    
new C().bar()