Invalid duplicate class definition in Groovy

Just a quick one. I’ve just started poking around with Groovy and from time to time I’d get an error saying…and I quote:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed,
/.../Error.groovy: 1: Invalid duplicate class definition of class Error :


An example might come handy:
I create a new file called Error.groovy, containing this:

class Error{
	def fail(){
		println 'hello'
	}
}

Error error = new Error()
error.fail()

When trying to run this, instead of a line saying hello, you’ll receive this heartwarming message:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed,
/.../Error.groovy: 1: Invalid duplicate class definition of class Error :
The source /.../Error.groovy contains at least two defintions of the
class Error.
One of the classes is a explicit generated class using the class statement,
the other is a class generated from the script body based on the file name.
Solutions are to change the file name or to change the class name.
 @ line 1, column 1.
   class Error{
   ^

1 error

After some general wondering I found this blog post explaining very nicely what the problem is.

If you’re busy I’ll tell you what the problem is, so you don’t have to click the link, just remember, this is not something that I discovered, all credit goes to the original blog poster.

OK, the problem is that I try to create a new instance of the Error class outside of any classes. Groovy will treat this as a script. Behind the scenes Groovy will create a class to store the script code in. This class will be named like the file in which it is used. In my case the file is called Error.groovy, so Groovy will try to create a new class called Error…..however, this class allready exists in the file and so Groovy get’s all moody and refuses any further cooperation.

The solution in my case would be to either:

  1. Create a public static void main method in my Error class and call the Error code from there
  2. Rename my class to something other than Error

Either way, it’ll work.
Hope this is of any usage to you.

One thought on “Invalid duplicate class definition in Groovy”

Leave a Reply

Your email address will not be published. Required fields are marked *