[ 
https://issues.apache.org/jira/browse/GROOVY-9986?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17303159#comment-17303159
 ] 

Paul King commented on GROOVY-9986:
-----------------------------------

See also comments in GROOVY-9985.

Currently {{val as MyClass}} becomes (more or less) {{asType(val, MyClass)}} 
and then type checking is run and since {{asType}} exists for {{Object}} and 
any Class, checking always succeeds. We could try to make `as` coercion smarter 
and know about the current built-in coercions or provide a type checker which 
did the same that could be optionally applied.

Secondly, the {{List}} to array coercion doesn't currently attempt to call 
{{asType(listElement, componentType)}} for each of its elements. We could 
consider doing that but have resisted previously since it is an extra level of 
magic which users can do themselves, e.g. for valid inputs:
{code}
Integer[] arr2 = [1, "42", new Date().time].collect{ it as Integer }
{code}
Again, "as" is acting as an escape hatch here, so it doesn't really help in 
detecting an invalid case such as adding "two" into above list.

> CLONE - STC does not report type mismatches for coerced list expression
> -----------------------------------------------------------------------
>
>                 Key: GROOVY-9986
>                 URL: https://issues.apache.org/jira/browse/GROOVY-9986
>             Project: Groovy
>          Issue Type: Bug
>          Components: Static Type Checker
>            Reporter: Thodoris Sotiropoulos
>            Assignee: Paul King
>            Priority: Major
>
> The following program compiles (with @CompileStatic), although it shouldn't.
> {code:java}
> public class Main {
>     public static void main(String[] args) {
>       // Integer[] arr = new Integer[]{1, "str"}; // does not report error 
> (see GROOVY-9985)
>       Integer[] arr2 = [1, "fda"] as Integer[] // does not report error
>     }
> }
> {code}
> As a result, an exception is thrown at runtime
> {code:java}
> Exception in thread "main" 
> org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast 
> object 'str' with class 'java.lang.String' to class 'java.lang.Integer'
>         at 
> org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToNumber(DefaultTypeTransformation.java:172)
>         at 
> org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:282)
>         at 
> org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:243)
>         at 
> org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(IndyInterface.java:318)
>         at Main.main(test.groovy:4)
> {code}
> Tested on 
> [https://github.com/apache/groovy/commit/f0eea862549529ef4e93fafe337f86dd4ac98751]
>  



--
This message was sent by Atlassian Jira
(v8.3.4#803005)

Reply via email to