Groovy Closures and Java Functional Interfaces: Does SAM Coercion Preserve Delegate-Based Method Resolution?
0 reputation · 03 Jun 2022, 21:18 UTC
When a Groovy closure is exposed to Java code through a functional interface such as java.util.function.Function or Consumer, the conversion can be performed with the as operator or under @CompileStatic. The resulting Java SAM type hides the closure’s Groovy-specific owner and delegate properties from the Java caller, but it is unclear whether the underlying groovy.lang.Closure instance continues to resolve method calls against its current delegate after the coercion has occurred.
In dynamic Groovy, reassigning a closure’s delegate at runtime changes method resolution and is central to DSL behavior. If a Java consumer invokes the SAM method after that reassignment, the expected outcome depends on whether the adaptation layer captures the original owner context or forwards calls through the live closure object. The distinction matters for libraries that accept Groovy callbacks and later mutate their delegates, especially when the same closure instance is shared across Groovy and Java boundaries.
Does coercing a Groovy closure to a Java functional interface preserve the live delegate lookup for subsequent SAM invocations? If the delegate is mutated after conversion, does the Java caller observe the new resolution target or the original owner? Are these semantics stable across Groovy 3 and Groovy 4 without additional annotations?