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

If/else branch does not always infer the variable type

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Open
    • Minor
    • Resolution: Unresolved
    • 2.0.0, 2.5.23, 4.0.14, 3.0.19
    • None
    • Static Type Checker
    • None

    Description

      Suppose we have the following code:

      class A {
        void m() {  
        }
      }
      class B extends A {
      }
      class C extends A {
      }
      
      @groovy.transform.TypeChecked
      class Test {
      
         void m() {
            def var = new Object()   //If instead I put just "def var" it works as spected
            if (true) {
              var = new B()
            }
            else {
              var = new C()
            }
            var.m()                  //fails here
         }
      }
      

      In this case, after the if/else structure we can infer that var is instanceOf A.
      But, the initialization seems to confuse the type inference.

      [Static type checking] - Cannot find matching method java.lang.Object#mA()
      at line: 23, column: 7

      If instead of

      def var = new Object()

      we put just

      def var

      , then the inference works fine.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              ariel.andres.morelli Ariel Morelli Andres
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated: