Details
-
Bug
-
Status: Closed
-
Minor
-
Resolution: Fixed
-
2.5.22, 3.0.18, 4.0.13
-
None
Description
I'm not sure if its a bug or I am doing something wrong, but it is a little bit strange:
Consider the following class:
// code placeholder @CompileStatic static class Search { private String keyword private Pattern pattern private int code = 0 void setCriteria(String keyword) { this.keyword = keyword code = 1 } void setCriteria(Pattern pattern) { this.pattern = pattern code = 2 } int getCode() { return code } }
Now if you execute:
// code placeholder String kw = "something" assert new Search( criteria: kw ).code == 1 Pattern p = ~/\w+/ assert p instanceof Pattern assert new Search( criteria: p ).code == 2 // fails as value returned is 1
It fails as it is calling the `setCriteria(String)` instead of `setCriteria(Pattern)`. I'm not sure if that is the expected behavior.
One thing to note is that the above code works without issues when compiling dynamically.
Another strange behavior is that if `setCriteria(Pattern)` is declared before `setCriteria(String)`, it fails to compile:
// code placeholder @CompileStatic static class Search { private String keyword private Pattern pattern private int code = 0 // Pattern before String: void setCriteria(Pattern pattern) { this.pattern = pattern code = 2 } void setCriteria(String keyword) { this.keyword = keyword code = 1 } int getCode() { return code } } new Search( criteria: "hello" // <---- will fail here )
The error thrown is:
Cannot cast object 'hello' with class 'java.lang.String' to class 'java.util.regex.Pattern'
Again, without `@CompileStatic` works fine.
It seems to happen in all Groovy versions (2.X, 3.X and 4.X).
NOTE: I maintain a library which is developed with Groovy, but that can be used from Java or Kotlin, for that reason I need to support `Pattern` class outside Groovy.
I have created a testing code in case you need it:
https://gitlab.com/intellisrc/groovy-bugs/-/tree/string-pattern
Attachments
Issue Links
- relates to
-
GROOVY-11451 IncompatibleClassChange with map-style constructor and overloaded setters
- Closed