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

Problem with @TypeChecked and switch statements

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Critical
    • Resolution: Fixed
    • 2.1.5
    • 2.1.6
    • Compiler
    • None

    Description

      Demo.groovy
      import groovy.transform.CompileStatic
      
      @CompileStatic
      class Demo {
      
          def processNumber(int x) {
              def value = getValueForNumber(x)
              value
          }
      
          def getValueForNumber(int x) {
              def valueToReturn
              switch(x) {
                  case 1:
                      valueToReturn = 'One'
                      break
                  case 2:
                      valueToReturn = []
                      valueToReturn << 'Two'
                      break
              }
              valueToReturn
          }
      
          static void main(args) {
              def demo = new Demo()
              println demo.processNumber(1)
              println demo.processNumber(2)
              println demo.processNumber(3)
          }
      }
      

      That code will throw a ClassCastException.

       $ groovy Demo
      Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'One' with class 'java.lang.String' to class 'java.util.List'
      org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'One' with class 'java.lang.String' to class 'java.util.List'
      	at Demo.processNumber(Demo.groovy:7)
      	at Demo.main(Demo.groovy:27)
      

      The compiler is generating the following code for the processNumber method:

       @TypeChecked.TypeCheckingInfo(inferredType="AAlDbGFzc05vZGUAABBMamF2YS91dGlsL0xpc3Q7AQAAAAEBAAAJQ2xhc3NOb2RlAAASTGphdmEvbGFuZy9PYmplY3Q7AQAAAAEBAAAJQ2xhc3NOb2RlAAADTEU7Af////8A/////wAAAAABAAlDbGFzc05vZGUAABJMamF2YS9sYW5nL09iamVjdDsA/////w==", version=1)
        public Object processNumber(int x)
        {
          List value = (List)ScriptBytecodeAdapter.castToType(getValueForNumber(x), List.class);
          return value; return null;
        }
      

      It appears that the compiler is picking up the type from whatever the last case statement is.

      Attachments

        Activity

          People

            melix Cédric Champeau
            brownj Jeff Brown
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: