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

Type mismatch when encountering unconditional flow typing and null

Attach filesAttach ScreenshotVotersWatch issueWatchersCreate sub-taskLinkCloneUpdate Comment AuthorReplace String in CommentUpdate Comment VisibilityDelete Comments
    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 4.0.5, 3.0.20
    • Static Type Checker
    • None

    Description

      I don't know if this is a bug or a feature

      I have the following program

      
      class A {}
      
      class Test {
        void test() {
          def x = new A() // type of x is A
          x = null; // type of x becomes Object
      
          A y = x
        }
      
        void test2() {
          def x = new A()
          if (true) {
            x = null
          }
          A y = x // compiles as expected
      
        }
      }
      

      Actual behavior

      org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
      test.groovy: 9: [Static type checking] - Cannot assign value of type java.lang.Object to variable of type A
       @ line 9, column 11.
             A y = x
                   ^
      
      1 error
      

      Expected behavior

      Compile successfully

      The issue here is that when the compiler encounters a `null` assignment to a `def` variable, it changes the previously-inferred type of the variable to `Object`. Probably, this is not necessary as `null` is assignable to any type.

      Tested against master (commit: ee12bb52381e8f0583c61fc25d43de1f55b80a87)

      Attachments

        Activity

          This comment will be Viewable by All Users Viewable by All Users
          Cancel

          People

            emilles Eric Milles
            theosot Thodoris Sotiropoulos
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Slack

                Issue deployment