Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Number:

GEP-11

Title:

SAM coercion

Version:

3

Target Version:Groovy 2.2 / 2.2+

Type:

Feature

Status:

Draft

Leader:

Jochen Theodorou

Created:

2013-05-30

Last modification:

2013-0607-1801

Table of Contents
maxLevel2
excludeMetadata

...

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
themeConfluence
languagegroovy
interface SAM1 { def foo(String s)}
interface SAM2 { def bar(Integer i)}
def method(x, SAM1 s1){s1.foo(x)}
def method(x, SAM2 s2){s2.bar(x)}
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
themeConfluence
languagegroovy
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: http://cr.openjdk.java.net/~dlsmith/jsr335-0.6.1/F.html

References

Mailing-list discussions

...