I'm studying Groovy at the moment, and I have a question related to unexpected behavior when using anonymous classes.
So, I've learned that Groovy autogenerates smart constructors that can destructure the provided hashmap and set the given values to the corresponding properties:
class Greeter {
String name
}
def alice = new Greeter(name: "Alice")
println "Hello, $alice.name" // "Hello, Alice"
Also, I've learned that it is possible to create derived classes anonymously like shown below:
def bob = new Greeter() {
def greet() {
println "Hello, $name"
}
}
bob.name = "Bob"
bob.greet() // "Hello, Bob"
However, what I can't comprehend is what exactly is wrong with this scenario:
def chuck = new Greeter(name: "Chuck") {
def greet() {
println "Hello, $name"
}
}
chuck.greet(); /*
Caught: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Greeter(LinkedHashMap)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Greeter(LinkedHashMap)
at anonymous-class$2.<init>(anonymous-class.groovy)
at anonymous-class.run(anonymous-class.groovy:17)
*/
So, here I basically combine the first and the second feature, and something breaks behind the curtains. Is that a known behavior or a bug?
Thanks in advance!