Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-6479

Closure to SAM interface coercion doesn't handle contravariant types correctly

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 2.3.0-beta-1
    • Static Type Checker
    • None

    Description

      When coercing a closure to an interface where the method takes a contravariant type, Groovy should create an implementation that accepts the most special type.

      class TestCase {
      
        interface Action<T> {
          void execute(T thing)
        }
      
        static class Wrapper<T> {
      
          private final T thing
      
          Wrapper(T thing) {
            this.thing = thing
          }
      
          void contravariantTake(Action<? super T> action) {
            action.execute(thing)
          }
      
          void invariantTake(Action<T> action) {
            action.execute(thing)
          }
      
        }
      
        static <T> Wrapper<T> wrap(Callable<T> callable) {
          new Wrapper(callable.call())
        }
      
        static Integer dub(Integer integer) {
          integer * 2
        }
      
        static void main(String[] args) {
          wrap {
            1
          } contravariantTake {
            dub(it) // fails static compile, 'it' is not known to be Integer
          }
      
          wrap {
            1
          } invariantTake {
            dub(it) // passes static compile, 'it' is known to be Integer
          }
        }
      
      }
      

      Attachments

        Issue Links

          Activity

            People

              melix Cédric Champeau
              ldaley Luke Daley
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: