Details
-
Bug
-
Status: Closed
-
Major
-
Resolution: Fixed
-
4.0.7, 4.0.8, 4.0.9
-
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.