22 Apr 2004 10:19
Re: constructor calls and named parameters
On 21 Apr 2004, at 17:41, John Stump wrote:
> Hello, I am having some confusion about constructors and named
> parameters.
>
> It seems that named parameter passing is supported in
> constructor calls. For instance, I can do this:
>
> class A {
> x = 0; y = 0; z = 0
> }
>
> s = new A(x:1, y:2, z:3)
>
> assert s.x == 1
> assert s.y == 2
> assert s.z == 3
>
> However, if I have my own constructor like this:
>
> class AA {
> x = 0; y = 0; z = 0
>
> AA() {
> println "hello from AA ctor!"
> }
> }
BTW you positive that AA() is a no-arg constructor?
>
> s = new AA(x:1, y:2, z:3)
>
> assert s.x == 1
> assert s.y == 2
> assert s.z == 3
>
> the assertions fail, because all the properties are still 0. It
> seems that the named parameters were ignored.
>
> 1) Should groovy let me new AA with named parameters when there
> was a defined ctor?
It should - this seems like a bug. Though the current implementation of
named parameters is quite simple. Named parameters typically make a Map
and that is used to try construct you type, or the default no-arg
constructor is used and then the named parameters are set as bean
properties.
So
class Foo {
Foo(Map args) { ... }
}
or
class Foo {
Foo() { ... }
Integer x
String y
}
etc should be usable via
new Foo(x:123, y:"hey")
> 2) Should groovy make the assignments from the Map before
> invoking the constructor?
>
> 3) If I need to define a ctor, but also want to use the named
> parameter syntax, do I need to create a ctor that takes a Map?
Yes - or zero arg constructor. One day we hope to have full metadata
available so that we can know the names of each parameter in a
method/constructor and so do the unpicking of the Map automatically.
> If so, is there an easy way to apply the Map contents to set my
> properties?
There's a helper method if you need it...
InvokerHelper.setProperties(bean, map)
(which is in the org.codehaus.groovy.runtime package).
When we support optional modules (class augmentations) we should
probably have a 'setProperties' method available inside Groovy scripts.
James
-------
http://radio.weblogs.com/0112098/
RSS Feed