Groovy MultipleCompilationErrorsException

Note: I’ve been learning Groovy of late. It helps me learn a concept if I can ‘splain it, so I’ll be posting things I come across in an attempt to explain it written form. Dig?

Coming to Groovy from Java–and having learnt Ruby on the way–I came across an error that mystified me.
I had the following code in a file called Book.groovy:

class Book {
private String title
Book(String title) {
this.title = title
}
String getTitle() {
return title
}
}
Then, in the same file, below this class definition, I had this:

Book myBook = new Book(“War and Peace”)
println myBook.getTitle()
println getTitleBackwards(myBook)
String getTitleBackwards(book) {
String title = book.getTitle()
return title.reverse()
}
This is something that is allowable in a language such as Ruby. However, when trying to run the script, I received a MultipleCompilationErrorsException, with the message:
“The source Book.groovy contains at least two definitions of the class Book.
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.”
When I include the same code in a file named something other than Book.groovy–say, myFile.groovy–the script works as expected. Just something I find interesting.
Note that if I have the Book class definition in a separate class Book.groovy, and the exercising code in a separate file myFile.groovy, it works as well. This means that you don’t have to explicitly compile Book object code to use book objects. The only prerequisite is that Book.java must be on the classpath. It doesn’t even have to be in the same directory as the client code file.

Advertisements

About buffalobillion

Web Developer, JavaScript Balrog, Java dude, Ruby/Rails enthusiast. Guitar Playa.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s