Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »





SAM coercion








Jochen Theodorou



Last modification:



SAM stands for Single Abstract Method.  SAM coercion is here a Groovy style transformation of a groovy.lang.Closure instance into an object suitable for our SAM type. A SAM type is an abstract class or interface with a single abstract method. The coercion can happen as part of an assignment or as the result of a method call. Since this transformation might be outside of the types provided by Closure itself, it can be more than a simple Java style cast. Closure becomes a kind of sub type to all SAM types. Groovy has other such transformations without explicit cast or asType usage, which are number object transformations as well as the conversion of GString to String.


Even before Java8 we had discussions about supporting different interfaces with Closure like Runnable and Callable. These two being easy cases, any framework can define a myriad of interfaces and abstract classes. This then requires to "groovify" the library by writing a helper layer capable of transforming Closure objects into something the library then understand. While it is unlikely of this approach to make Groovy Builder surplus, it can still help with a more simple integration.

Meaning of  "Single Abstract Method"

For a SAM type to be a SAM type according to this GEP an abstract class or interface with a single abstract method is required. Any static methods, as well as non-abstract methods are not counted. The abstract method may be defined in the SAM class itself, but it can also be a parent. The required visibility modifier for the method is public though.

SAM examples:

  • Simple Interface:

  • Interface with defender method (aka virtual extension method):

  • Interface inheriting from another interface:

  • Interface inheriting from another interface, but not defining a method on its own:

  • simple abstract class

  • abstract class with a abstract and a non abstract method:

  • abstract class extending other class:

  • abstract class implementing interface:

Non-SAM examples:

  • empty interface:

  • interface with two methods:

  • abstract class with two abstract methods:

  • empty abstract class:

Influence on method selection


Influence on static typing system



Mailing-list discussions

JIRA issues


  • No labels