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

Leonard Brünings commented on GROOVY-10936:
-------------------------------------------

Thanks for the fix Eric

> Patterns conditionally created using pattern operator ~ are cast to 
> String/GString
> ----------------------------------------------------------------------------------
>
>                 Key: GROOVY-10936
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10936
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 4.0.7, 4.0.8, 4.0.9
>            Reporter: Pavlo Shevchenko
>            Assignee: Eric Milles
>            Priority: Major
>             Fix For: 3.0.20, 5.0.0-alpha-4, 4.0.17
>
>
> *Summary*
> If the value of the Pattern object is based on some argument evaluated at 
> runtime, then such objects will be created as String/GString instead of 
> Pattern.
> This used to work in 4.0.6, but started failing in 4.0.7.
> *Reproducer*
> {code:java}
> class Reproducer {
>     static void main(String... args) {
>         def random = new Random()
>         def staticPatternSlashy = ~/some static pattern \w+/
>         def staticPatternGString = ~"some static pattern \\w+"
>         def dynamicPatternSlashy = random.nextInt() % 2 == 0 ? ~/pattern one 
> \w+/ : ~/pattern two \w+/
>         def dynamicPatternGString = random.nextInt() % 2 == 0 ? ~"pattern one 
> \\w+" : ~"pattern two \\w+"
>         assert staticPatternSlashy instanceof Pattern       // succeeds
>         assert staticPatternGString instanceof Pattern      // succeeds
>         assert dynamicPatternSlashy instanceof Pattern      // fails
>         assert dynamicPatternGString instanceof Pattern     // fails
>     }
> } {code}
> *Workaround*
> Explicitly declaring the variable as Pattern does not work and fails at 
> runtime as it will attempt to cast the String to Pattern. Creating the 
> pattern using Pattern.compile()  works, but is a nasty refactoring and 
> eliminates the benefits of the operator.



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

Reply via email to