Skip to content

Instantly share code, notes, and snippets.

@purplefox
Created April 4, 2012 12:46
Show Gist options
  • Save purplefox/2300852 to your computer and use it in GitHub Desktop.
Save purplefox/2300852 to your computer and use it in GitHub Desktop.
It's nice being able to set properties by passing them to the constructor in Groovy:
def foo = new Foo(bar: 23, wibble: "hello")
But if Foo is created via a factory method instead:
def foo = Foo.createFoo(bar: 23, wibble: "hello")
It doesn't work
where
class Foo {
.. properties
static Foo createFoo() {
return new Foo();
}
}
How can I get this to work with factories?
@pledbrook
Copy link

If I understand you correctly, you want Groovy to recognise the factory pattern and automatically pass the factory method arguments through to the constructor of the created instance? Not sure any language does that :) You can always manage it via AST transforms, but that seems like wasted effort.
Anyway, what you have currently is what I would do, although I would probably make the Map the first argument of the constructors rather than the second.

@purplefox
Copy link
Author

No, I don't mean that.

I know Groovy can automatically apply properties without me having to code any manual property application code if I call a no arg constructor:

I.e.

class Foo {
  Foo() {
  }
}

This allows me to construct the object like so:

def foo = new Foo(port:80, host: "localhost")

The problem is my Foo class already takes another arg in its constructor (which is not a property), i.e. Foo is really like this:

class Foo {
  Foo(someOtherParam) {
  }
}

I was hoping that Groovy would still automatically apply params in this case, i.e. allow me to do:

def foo = new Foo("wibble", [port:80, host: "localhost"])

but that doesn't seem to work.

hence.. I am applying the params manually

@pledbrook
Copy link

OK, I finally understand. You're right, you can't get automatic property binding once you're no longer using the default constructor. I've been told it may be worth a JIRA :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment