You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Eric Milles (Jira)" <ji...@apache.org> on 2022/05/15 16:55:00 UTC

[jira] [Commented] (GROOVY-10623) Type mismatch when encountering unconditional flow typing and null

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

Eric Milles commented on GROOVY-10623:
--------------------------------------

Current logic in {{StaticTypeCheckingVisitor}} when assigning null to expression is to revert to declared type:
{code:groovy}
    protected void storeType(final Expression exp, ClassNode cn) {
        if (cn == UNKNOWN_PARAMETER_TYPE) {
            // this can happen for example when "null" is used in an assignment or a method parameter.
            // In that case, instead of storing the virtual type, we must "reset" type information
            // by determining the declaration type of the expression
            cn = getOriginalDeclarationType(exp);
        }
        ...
{code}

I suppose if declared type is dynamic ("def", "var", "final", etc.) it could be ...

> Type mismatch when encountering unconditional flow typing and null
> ------------------------------------------------------------------
>
>                 Key: GROOVY-10623
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10623
>             Project: Groovy
>          Issue Type: Bug
>          Components: Static Type Checker
>            Reporter: Thodoris Sotiropoulos
>            Assignee: Eric Milles
>            Priority: Major
>
> I don't know if this is a bug or a feature
> I have the following program
> {code}
> 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
>   }
> }
> {code}
> h3. Actual behavior
> {code}
> 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
> {code}
> h3. 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)



--
This message was sent by Atlassian Jira
(v8.20.7#820007)