jrk
jrk

Reputation: 696

Groovy closures, def vs typed return value

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

Upvotes: 2

Views: 260

Answers (1)

tim_yates
tim_yates

Reputation: 171144

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()

Upvotes: 3

Related Questions