Table of Contents

Groovy Basics

General Code Appearance

  • Groovy looks much like C and Java
  • Groovy has 3 kinds of comments
    • #! – allowed only on the first line
    • // – single line
    • /* */ – multiline – same as Java and C
    • Most Groovy syntax is similar to, but not identical to the same syntax in Java
  • Groovy allows you to leave out parentheses in some cases, but you should be careful when you do so, because it might lead to ambiguity
    • Why do you allow it, then?

The assert statement

  • Groovy includes an assert keyword that takes in statements and evaluates them and halts the program if they're false

Groovy at a glance

  • Class declarations

    class Book {
        private String title
        Book (String theTitle) {
            title = theTitle
        String getTitle() {
            return title
    • Note the lack of semicolons
    • Other than that, everything is pretty Java-ish
    • Each class should be saved in a file named for that class – the Book class should be saved in a file called Book.groovy
  • Scripts
    • A script is a file that has Groovy statements without an enclosing class declaration

      Book gina = new Book("Groovy in Action")
      assert gina.getTitle() == "Groovy in Action"
      assert getTitleBackwards(gina) == "noitcA ni yvoorG"
      String getTitleBackwards(book) {
          return book.getTitle().reverse()
    • Can contain method definitions as well as plain statements
    • Note that a script is parsed completely before execution – unlike Python or Ruby, you may declare methods at the bottom of the file and use them at the top
    • Can use other classes as long as they're on the classpath without an explicit compilation step
    • You can tell this book was written for Java programmers
      • Did you know you can have methods outside of a class???????
      • Did you know you can run code without compiling it first?????
  • GroovyBeans
    • A JavaBean is a Java class that has a getter and setter method for all of the properties it wishes to expose
      • This is because Java is a terrible language which didn't have support for real properties until very recently
    • The naming scheme for JavaBean properties is get<name>() and set<name>(T value)
    • A GroovyBean is a JavaBean defined in Groovy
    • Groovy makes working with beans easier in the following 3 ways
      • Generates the accessor methods
      • Allows simplified access to all JavaBeans (including GroovyBeans)
      • Simplifies registration of event handlers and annotations that register a property as bindable
      • So far, my impression of the rationale behind Groovy is, "Java was so terrible, we had to make an entirely new language to overcome its shortcomings
      • Those three points above are handled natively in a decent programming language, like Python or C#
    • Example GroovyBean:

      class BookBean {
          String title
      def book = BookBean()
      book.setTitle("Groovy In Action")
      assert book.getTitle() == "Groovy In Action"
      book.title = "Groovy conquers the world"
      assert book.title == "Groovy conquers the world"
      • Note that this is a script even though it contains a class declaration
      • book.title is not a direct field access – it is a shortcut for book.setTitle() or book.getTitle() depending on usage
  • Annotations
    • Groovy allows you to use the same annotations as in Java
    • Groovy also has its own annotations, which are used to mark code for special handling by the compiler
    • Example @Immutable
      • Marking a bean as @Immutable makes its class final, all of its fields final and ensures that the bean's value cannot be changed after construction

        import groovy.transform.Immutable
        @Immutable class FixedBook {
            String title
        def gina = new FixedBook("Groovy in Action")
        def regina = new FixedBook(title: "Groovy in Action")
        assert gina.title == "Groovy in Action"
        assert gina == regina
        try {
            gina.title = "Oops"
            assert false "Should not be able to alter an immutable class"
        catch (ReadOnlyPropertyException expected) {
            println "Expected error: '$expected.message'"
      • In addition to the annotation, this snippet demonstrates a few other things:
        • try / catch works much the same as it does in Java
        • String interpolation: Can access variables by prefixing them with $, and can access properties on those variables
        • Can set properties explicitly when constructing a GroovyBean (useful when a GroovyBean has many properties)
        • Groovy defines .equals() for beans to compare property values rather than memory addresses

Author: Rohit Patnaik

Created: 2019-01-24 Thu 01:33