class Foo {
public Foo(String s) {}
}
print new Foo()
Why does this code work?
If I declare constructor with parameter of primitive type the script fails.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Groovy will do its best to do what you asked it to do. When you call
new Foo(), it matches the call to callingnew Foo( null )as there is a constructor that can take anullvalue.If you make the constructor take a primitive type, then this cannot be
null, so Groovy throws aCould not find matching constructor for: Foo()exception as you have seen.It does the same with methods, so this:
prints
Hello tim(as both constructor and method are called with a null parameter)wheras:
prints
Hola MaxClarification
I asked on the Groovy User mailing list, and got the following response:
So there, it works (for now), but don’t rely on it 🙂