You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (Jira)" <ji...@apache.org> on 2025/05/08 08:42:00 UTC
[jira] [Commented] (GROOVY-11657) Improved compatibility for "Support instanceof variable"
[ https://issues.apache.org/jira/browse/GROOVY-11657?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17950220#comment-17950220 ]
Paul King commented on GROOVY-11657:
------------------------------------
This is another variation:
{code:groovy}
public class JEP394 {
public static void main(String[] args) {
List<?> items = List.of("Pi", "Cat", "Camel", 3.14, new ArrayList<>());
for (Object item : items) {
if (item instanceof String s && s.length() < 3) {
System.out.println(s.toUpperCase());
}
if (item instanceof String s && s.length() > 3) {
System.out.println(s.toUpperCase());
}
if (!(item instanceof String s)) {
return;
}
System.out.println(s.equalsIgnoreCase("Dog"));
}
}
}
// PI false false camel false
{code}
Adding this as another case and noting that we don't (currently) support the not instanceof syntax for the last {{if}} statement: {{item !instanceof String s}}
Given this is really a Java compatibility feature, I don't think we need this last case.
> 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)