Hilikus
Hilikus

Reputation: 10331

Groovy Closure reuse vs rehydrate copy

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

Upvotes: 2

Views: 2244

Answers (1)

Igor
Igor

Reputation: 33983

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

Upvotes: 1

Related Questions