Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.





SAM coercion



Target Version:Groovy 2.2 / 2.2+






Jochen Theodorou



Last modification:


Table of Contents


Influence on method selection


The normal method selection algorithm tries to find the most specific method to the given argument runtime types and the most general for null. Since a SAM type and a target method parameter type are not in an inheritance relation "most specific" needs a redefinition in parts. It will be assumed the SAM type is like a direct child of the given target type, but if the SAM type is one implemented by Closure (Runnable and Callable), then no SAM coercion will be needed. This case is preferred in method selection. In case of a  overloaded method, where each can be used as target for the SAM coercion, method selection will thus fail, regardless their internal relation. In Groovy the actual method signature of the SAM type and the coercion target are not important. Also it is not important if the target type is an abstract class or an interface.

Example of two SAM targets with failing runtime method selection:

Code Block
interface SAM1 { def foo(String s)}
interface SAM2 { def bar(Integer i)}
def method(x, SAM1 s1){}
def method(x, SAM2 s2){}
method (1)   {it}  // fails because SAM1 and SAM2 are seen as equal
method ("1") {it}  // fails because SAM1 and SAM2 are seen as equal

Example of SAM type being ignore as a non-coercion case is available:

Code Block
interface SAM {def foo(String s)}
def method(SAM s) {1}
def method(Runnable r) {2}
assert method {it} == 2

Influence on static typing system


The Scope for the static type system is split into a basic part  for Groovy 2.2 and an extended one for a later version (2.3 or 3.0)

Groovy 2.2 static checks

The type checking in Groovy 2.2 will be limited to mimic the behavior of normal Groovy. No method signature checks are performed, as well as there will be no additional test or method selection based on the type provided by the open block.

Groovy 2.2+ static checks

In later versions of Groovy the static type checker has to be improved to refine method selection by the given type signature through the open block or lambda. A SAM type is then a fitting type for the coercion only if the provided types and the target types in the SAM are matching by number and type itself. A more detailed description can be found here:


Mailing-list discussions