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.