2

In the DSL page of groovy they show this

def email(Closure cl) {
  def email = new EmailSpec()
  def code = cl.rehydrate(email, this, this)
  code.resolveStrategy = Closure.DELEGATE_ONLY
  code()
}

Why are they calling rehydrate instead of just assigning the delegate to the closure:

def email(Closure cl) {
  def email = new EmailSpec()
  cl.delegate = email
  cl.resolveStrategy = Closure.DELEGATE_ONLY
  cl()
}

In other words, why do we need a copy of the closure instead of reusing the one given. I don't necessarily see a problem with using rehydrate but I also don't see the need, which tells me there's something I'm not understanding

Hilikus
  • 9,954
  • 14
  • 65
  • 118
  • `rehydrate` doesn't just set the delegate – tim_yates Nov 11 '16 at 23:05
  • @tim_yates I know, it creates a clone. My question is more why does the doc recommend a clone instead of reusing the same object and avoid creating a new object. There must be a reason – Hilikus Nov 14 '16 at 15:36

1 Answers1

1

I imagine it returns a copy rather than reusing the same closure in order to stay idempotent/safe in case you still need a reference to the old closure.

As @tim_yates mentioned, the rehydrate method sets the delegate, owner, and thisObject, whereas your second example only sets the delegate. It's not that the rehydrate method does anything magical, it's just a convenience method so you don't have to set all three properties individually/line-by-line.

I also believe rehydrate is meant to work with its partner method dehydrate, which returns a copy of the closure with those three fields cleared (allowing rehydrate to easily re-set them).

Igor
  • 33,276
  • 14
  • 79
  • 112