[ https://issues.apache.org/jira/browse/GROOVY-11657?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17950395#comment-17950395 ]
Paul King commented on GROOVY-11657: ------------------------------------ The FinalVariableAnalyzer may be close to what we need, not sure. I don't see this as high priority, it might even be bad code style in some folks eyes if you are relying on code like that. But this issue at least documents the difference to Java and it would be nice to eventually close that gap if we can. I stumbled upon code like this when looking for good examples for the Groovy 5 release notes. > Improved compatibility for "Support instanceof variable" > -------------------------------------------------------- > > Key: GROOVY-11657 > URL: https://issues.apache.org/jira/browse/GROOVY-11657 > Project: Groovy > Issue Type: New Feature > Components: class generator, parser-antlr4 > Reporter: Daniel Sun > Assignee: Eric Milles > Priority: Minor > Fix For: 5.0.0-alpha-13 > > > Java's pattern matching for {{instanceof}} supports flow-sensitive scoping, > see: > * https://stackoverflow.com/a/73749721 > * JLS 6.3.1, "Scope for Pattern Variables in Expressions" > * > https://openjdk.org/projects/amber/design-notes/patterns/pattern-match-semantics > So, for the class below, the variable {{s}} would still be in scope for the > last {{println}} statement. > {code:java} > import java.util.ArrayList; > import java.util.List; > public class JEP394 { > public static void main(String[] args) { > List<?> items = List.of("Pi", "Cat", 3.14, new ArrayList<>()); > for (Object item : items) { > if (item instanceof String s && s.length() < 3) { > System.out.println(s.toUpperCase()); > } else if (item instanceof Number n && n.intValue() < 5) { > System.out.println(n.doubleValue()); > continue; > } else { > if (item instanceof String s) { > System.out.println(s.toLowerCase()); > } else { > System.out.println(item); > } > continue; > } > System.out.println(s); > } > } > } > // PI Pi cat 3.14 [] > {code} > Currently we report an error for this case (for both static and dynamic > natures). -- This message was sent by Atlassian Jira (v8.20.10#820010)