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

Union types incorrectly resolved

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.4.13, 2.5.3
    • 4.0.5, 2.5.19, 3.0.13
    • Compiler
    • None

    Description

      UsingĀ @CompileStatic breaks Map#put if the operand is a UnionType due to this change (found by using git bisect): https://github.com/apache/groovy/commit/2e4413812fff5d2033e9eb163d734b539b079b6b

      Error:

      src/main/groovy/pkg/Main.groovy: 12: [Static type checking] - Cannot call java.util.LinkedHashMap <java.lang.String, pkg.Foo>#put(java.lang.String, pkg.Foo) with arguments [java.lang.String, <UnionTypepkg.Foo+pkg.Bar>]

      Sample code:
      Bar.groovy:

      package pkg
      
      interface Bar {String name()}
      

      Foo.groovy

      package pkg
      
      interface Foo {}
      

      Main.groovy

      package pkg
      
      import groovy.transform.CompileStatic
      
      @CompileStatic
      class Main {
          static main(args) {
              Map<String, Foo> map = [:]
              map.values().each { Foo foo ->
                  if (foo instanceof Bar) {
                      String name = (foo as Bar).name()
                      map.put(name, foo)
                  }
              }
          }
      }
      

      There is a workaround for this, which is to explicitly cast the variable to the Map's type. Changing line 12 to map.put(name, (Foo) foo) will allow the code to compile. However, this is clearly not the expected behavior.

      Attachments

        Activity

          People

            emilles Eric Milles
            kenzierocks Octavia Togami
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: