12
\$\begingroup\$

I am new to Groovy and I am having a little problem with constructors of subclasses. Basically, I have a base abstract class like

class BaseClass {
 def BaseClass(Map options) {
 // Does something with options,
 // mainly initialization.
 }
 // More methods
}

and a bunch of derived classes like

class AnotherClass extends BaseClass {
 // Does stuff
}

I would like to be able to create instances like

def someObject = new AnotherClass(foo: 1, bar: 2)

Unfortunately, Groovy creates automatically all sorts of constructors for AnotherClass, with various signatures - based on the properties of AnotherClass - but will not allow me to just reuse the constructor in BaseClass. I have to manually create one like

class AnotherClass extends BaseClass {
 def AnotherClass(options) {
 super(options)
 }
 // Does stuff
}

It feels repetitive doing so for each subclass, and it is probably the wrong way.

What would be the Groovy way to share some logic in the constructor?

asked Jul 16, 2012 at 7:28
\$\endgroup\$

1 Answer 1

19
\$\begingroup\$

@InheritConstructors is probably what you are looking for:

@InheritConstructors
class AnotherClass extends BaseClass {}

will create the constructors corresponding to the superclass constructors for you.

answered Jul 16, 2012 at 7:39
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Thank you very much, this is exactly what I was looking for! By the way, for possible future readers, InheritConstructors lives in the package groovy.transform. \$\endgroup\$ Commented Jul 16, 2012 at 8:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.