Error while executing groovy script

The code looks like this:

class Book
{
     private String title
     Book (String theTitle)
     {
         title=theTitle
     }
     String getTitle()
     {
         return title
     }
}
Book gina=new Book('Groovy in Action')
assert gina.getTitle()=='Groovy in Action'
assert getTitleBackwards(gina)=='noitcA ni yvoorG'
String getTitleBackwards(Book)
{
    title=book.getTitle()
    return title.reverse()
}

      

When I execute this with Ctrl + R I get the following compilation error.

1 compilation error:

Invalid class definition for class Book: The source Book.groovy contains at least two definitions for the Book class. One of the classes is an explicitly generated class using a class, the other is a class generated from the body of the script per filename. Solutions have to change the filename or change the class name. by row: 1, column: 1

Someone please explain to me what's going on here.

+5


source to share


2 answers


Invalid duplicate definition of the Book class:

The OP's code list has two parts:

  1. Defining the type of the Book class
  2. Great script that acts like a Book client

Groovy treats your * .groovy file as a script file or as a class definition file. A script file is a file that contains code that is outside the class definition. When Groovy compiles a script file, it implicitly creates a class to hold your code, and the implicit class is named Book.groovy.



The compiler will then try to create an additional Book class for the Book class defined in the groovy script, and an error occurs here because there are now actually two definitions of the Book class.

Compare: blog post with sample code for this error message

To define the Book class and client script in the same file, you can rename the file, for example, BookApp.groovy. Caveat: if you do this, the Book type can only be referenced from the script file, the Book type will not be found automatically by groovy even if the * .groovy file was found in the classpath.

+5


source


  • Groovy console buffer items (sources, classes, variables) inside, second click "run" might be different, first of all I agree. Almost all interpreter windows (in any language) have similar behavior.
  • has subtle differences when opened from a file, pasting into a window without a file, resulting in the name Book or ConsoleScript1, etc. (Groovy's "procedural" use has a hidden "object", hidden / default / generated name class from file, etc.)

This can be useful for ad-hoc programming (script mode), but is not always the best for true OOP.



PS. the code has a few bugs, too

0


source







All Articles