DevOps / Apache Groovy Interview questions
Explain the execution flow of a closure's delegation strategy?
When a closure is created, it captures references relevant to call resolution: this, the enclosing class instance where the closure syntax appears; owner, typically the same as this unless the closure is nested inside another closure, in which case owner is the enclosing closure; and delegate, initially the same as owner but explicitly reassignable afterward.
When the closure body references an unqualified name, a method call or property with no explicit target, Groovy resolves it by consulting owner and delegate in an order determined by the closure's resolveStrategy - OWNER_FIRST, the default, checks owner first and falls back to delegate only if owner doesn't resolve it, while DELEGATE_FIRST reverses that order.
Frameworks that build DSLs, like Gradle's configuration blocks, commonly reassign a closure's delegate to a builder or configuration object and set resolveStrategy to DELEGATE_FIRST, so that unqualified calls inside a user's configuration block resolve against that builder object instead of the surrounding class where the block happens to be written - this is exactly the mechanism that makes DSL-style nested configuration blocks work.
Two further strategies, OWNER_ONLY and DELEGATE_ONLY, skip the fallback step entirely and only ever consult one of the two, useful when a framework needs to guarantee calls resolve exclusively against the delegate, or exclusively against owner, with no possibility of accidentally falling through to the other.
More Related questions...