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/09/26 13:20:00 UTC

[jira] [Commented] (GROOVY-10769) Invalid code generated after instanceof test

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

Eric Milles commented on GROOVY-10769:
--------------------------------------

Can you try with 3.0.14-SNAPSHOT?

Also, you don't need to reference "instance" within the {{with}} block.  This creates an unnecessary closure shared variable.
{code:groovy}
def instance = ...
instance?.with {
  if (... || it instanceof A) { // it instead of instance
    m(name) // or it.name
  }
}
{code}

> Invalid code generated after instanceof test
> --------------------------------------------
>
>                 Key: GROOVY-10769
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10769
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 3.0.13
>            Reporter: Szczepan Kuzniarz
>            Priority: Major
>
> Code similar to (all classes have @CompileStatic annotation):
> {code:java}
> 01| class Base { String getName() { ... } }
> 02| class SubclassA extends Base {}
> 03| class SubclassB extends Base {}
> 04| 
> 05| def instance = produceSubclassInstance()
> 06| instance?.with {
> 07|     if ((some other condition) || (instance instanceof SubclassA)) {
> 08|         someMethod(instance.name)
> 09|     }
> 10| }{code}
> throws {{{}ClassCastException{}}}:
> {code:java}
> org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'SubclassB@...[...]' with class 'SubclassB' to class 'SubclassA' {code}
> in line 8 when method {{produceSubclassInstance()}} returns instance of {{{}SubclassB{}}}.
> Such a construction works fine on Groovy 3.0.12.
> Moreover after changing lines 6-10 to:
> {code:java}
> 06| if (instance != null) {
> 07|     if ((some other condition) || (instance instanceof SubclassA)) {
> 08|         someMethod(instance.name)
> 09|     }
> 10| } {code}
> it works fine on Groovy 3.0.13 too.
> It seems like the condition {{(instance instanceof SubclassA)}} forces compiler to assume concrete subtype inside the {{if}} block when the {{if}} block is inside closure.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)