Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10936

Patterns conditionally created using pattern operator ~ are cast to String/GString

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 4.0.7, 4.0.8, 4.0.9
    • 3.0.20, 5.0.0-alpha-4, 4.0.17
    • None
    • None

    Description

      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

      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
          }
      
      } 

      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.

      Attachments

        Activity

          People

            emilles Eric Milles
            pshevche Pavlo Shevchenko
            Votes:
            2 Vote for this issue
            Watchers:
            4 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: