Kalpana Kalpana (Editor)

Groovy (programming language)

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit
Designed by
  
James Strachan

Groovy (programming language)

Paradigm
  
Object-oriented, imperative, scripting

Developer
  
Guillaume Laforge (PMC Chair) Jochen Theodorou (Tech Lead) Paul King Cedric Champeau

First appeared
  
2003; 14 years ago (2003)

Stable release
  
2.4.8 / January 14, 2017; 55 days ago (2017-01-14)

Typing discipline
  
Dynamic, static, strong, duck

Apache Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform, is dynamically compiled to Java virtual machine (JVM) bytecode, and interoperates with other Java code and libraries. Groovy uses a Java-like curly-bracket syntax. Most Java code is also syntactically valid Groovy, although semantics may be different.

Contents

Groovy 1.0 was released on January 2, 2007, and Groovy 2.0 in July, 2012. Since version 2, Groovy can also be compiled statically, offering type inference, and performance near that of Java. Groovy 2.4 was the last major release under Pivotal Software's sponsorship which ended in March 2015. Groovy has since changed its governance structure to a Project Management Committee (PMC) in the Apache Software Foundation.

History

James Strachan first talked about the development of Groovy on his blog in August 2003. Several versions were released between 2004 and 2006. After the Java Community Process (JCP) standardization effort began, the version numbering changed and a version called "1.0" was released on January 2, 2007. After various betas and release candidates numbered 1.1, on December 7, 2007, Groovy 1.1 Final was released and immediately renumbered as Groovy 1.5 to reflect the many changes made.

In 2007, Groovy won the first prize at JAX 2007 innovation award. In 2008, Grails, a Groovy web framework, won the second prize at JAX 2008 innovation award.

In November 2008, SpringSource acquired the Groovy and Grails company (G2One). In August 2009 VMWare acquired SpringSource.

Strachan had left the project silently a year before the Groovy 1.0 release in 2007. In Oct 2016, Strachan stated "I still love groovy (jenkins pipelines are so groovy!), java, go, typescript and kotlin".

In March 2004, Groovy had been submitted to the JCP as JSR 241 and accepted by ballot. After 8 years of inactivity, the Spec Lead changed its status to dormant in April 2012.

On July 2, 2012, Groovy 2.0 was released, which, among other new features, added static compiling and static type checking.

When the Pivotal Software joint venture was spun-off by EMC Corporation (EMC) and VMware in April 2013, Groovy and Grails formed part of its product portfolio. Pivotal ceased sponsoring Groovy and Grails from April 2015. That same month, Groovy changed its governance structure from a Codehaus repository to a Project Management Committee (PMC) in the Apache Software Foundation via its incubator. Groovy graduated from Apache's incubator and become a top-level project in November 2015.

Features

Most valid Java files are also valid Groovy files. Although the two languages are similar, Groovy code can be more compact, because it does not need all the elements that Java needs. This makes it possible for Java programmers to learn Groovy gradually by starting with familiar Java syntax before acquiring more Groovy programming idioms.

Groovy features not available in Java include both static and dynamic typing (with the keyword def), operator overloading, native syntax for lists and associative arrays (maps), native support for regular expressions, polymorphic iteration, expressions embedded inside strings, added helper methods, and the safe navigation operator ?. to check automatically for null pointers (for example, variable?.method(), or variable?.field).

Since version 2 Groovy also supports modularity (being able to ship only the needed jars according to the project needs, thus reducing the size of groovy's library), type checking, static compiling, Project Coin syntax enhancements, multicatch blocks and ongoing performance enhancements using JDK7's invoke dynamic instruction.

Groovy provides native support for various markup languages such as XML and HTML, accomplished via an inline Document Object Model (DOM) syntax. This feature enables the definition and manipulation of many types of heterogeneous data assets with a uniform and concise syntax and programming methodology.

Unlike Java, a Groovy source code file can be executed as an (uncompiled) script if it contains code outside any class definition, if it is a class with a main method, or if it is a Runnable or GroovyTestCase. A Groovy script is fully parsed, compiled, and generated before executing (similar to Perl and Ruby). This occurs under the hood, and the compiled version is not saved as an artifact of the process.

GroovyBeans, properties

GroovyBeans are Groovy's version of JavaBeans. Groovy implicitly generates getters and setters. In the following code, setColor(String color) and getColor() are implicitly generated. The last two lines, which appear to access color directly, are actually calling the implicitly generated methods.

Groovy offers simple, consistent syntax for handling lists and maps, reminiscent of Java's array syntax.

Prototype extension

Groovy offers support for prototype extension through ExpandoMetaClass, Extension Modules (only in Groovy 2), Objective-C-like Categories and DelegatingMetaClass.

ExpandoMetaClass offers a domain-specific language (DSL) to express the changes in the class easily, similar to Ruby's open class concept:

Groovy's changes in code through prototyping are not visible in Java, since each attribute/method invocation in Groovy goes through the metaclass registry. The changed code can only be accessed from Java by going to the metaclass registry.

Groovy also allows overriding methods as getProperty(), propertyMissing() among others, enabling the developer to intercept calls to an object and specify an action for them, in a simplified aspect-oriented way. The following code enables the class java.lang.String to respond to the hex property:

The Grails framework uses metaprogramming extensively to enable GORM dynamic finders, like User.findByName('Josh') and others.

Dot and parentheses

Groovy's syntax permits omitting parentheses and dots in some situations. The following groovy code

can be written as

enabling the development of domain-specific languages (DSLs) which look like plain English.

Functional programming

Although Groovy is mostly an object-oriented language, it also offers functional programming features.

Closures

According to Groovy's documentation: "Closures in Groovy work similar to a 'method pointer', enabling code to be written and run in a later point in time". Groovy's closures support free variables, i.e. variables which have not been explicitly passed as a parameter to it, but exist in its declaration context, partial application (which it terms 'currying'), delegation, implicit, typed and untyped parameters.

When working on Collections of a determined type, the closure passed to an operation on the collection can be inferred:

A group of expressions can be written in a closure block without reference to an implementation and the responding object can be assigned at a later point using delegation:

Curry

Usually called partial application, this Groovy feature allows closures' parameters to be set to a default parameter in any of their arguments, creating a new closure with the bound value. Supplying one argument to the curry() method will fix argument one. Supplying N arguments will fix arguments 1..N.

Curry can also be used in the reverse direction (fixing arguments N to N-1) using rcurry.

Groovy also supports lazy evaluation, reduce/fold, infinite structures and immutability, among others.

XML and JSON processing

On XML and JavaScript Object Notation (JSON) processing Groovy employs the Builder pattern, making the production of the data structure less verbose. For example, the following XML:

Can be generated via the following Groovy code:

And also can be processed in a streaming way through StreamingMarkupBuilder. To change the implementation to JSON, the MarkupBuilder can be swapped to JsonBuilder.

To parse it and search for a functional language Groovy's findAll method can serve:

String interpolation

In Groovy, the string can be interpolated with variables and expressions by using GStrings:

GStrings containing variables and expressions must be declared using double quotes.

A complex expression must be enclosed in curly brackets. This prevents parts of it from being interpreted as belonging to the surrounding string instead of to the expression:

Expression evaluation can be deferred by employing arrow syntax:

Abstract syntax tree transformation

According to Groovy's own documentation, "When the Groovy compiler compiles Groovy scripts and classes, at some point in the process, the source code will end up being represented in memory in the form of a Concrete Syntax Tree, then transformed into an Abstract Syntax Tree. The purpose of AST Transformations is to let developers hook into the compilation process to be able to modify the AST before it is turned into bytecode that will be run by the JVM. AST Transformations provides Groovy with improved compile-time metaprogramming capabilities allowing powerful flexibility at the language level, without a runtime performance penalty."

Examples of ASTs in Groovy are:

  • Singleton transformation
  • Category and Mixin transformation
  • Immutable AST Macro
  • Newify transformation
  • Among others.

    Traits

    According to Groovy's documentation, "Traits are a structural construct of the language which allow: composition of behaviors, runtime implementation of interfaces, behavior overriding, and compatibility with static type checking/compilation."

    Traits can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword:

    Then it can be used like a normal interface using the keyword implements:

    Traits allow a wide range of abilities, from simple composition to testing.

    Adoption

  • eXo Platform, an Open Source Enterprise Social Collaboration Platform uses Groovy.
  • Wired.com uses Groovy and Grails for the Product Reviews standalone section of the website.
  • Though Groovy can be integrated into any JVM environment, the JBoss Seam framework provides Groovy, besides Java, as a development language, out of the box.
  • The European Patent Office (EPO) developed a dataflow programming language in Groovy "to leverage similarities in the processes for communicating with each individual country’s patent office, and transform them into a single, universal process."
  • Linkedin uses Groovy and Grails for some of their subsystems.
  • XWiki SAS uses Groovy as scripting language in their collaborative open-source product.
  • SoapUI provides Groovy as a language for webservice tests development.
  • Sky.com uses Groovy and Grails to serve massive online media content.
  • DataMelt integrates Groovy into a numeric and statistic data-analysis framework
  • vCalc.com uses Groovy for all of the user defined mathematics in its math crowd-sourcing engine.
  • Eucalyptus, a cloud management system, uses a significant amount of Groovy.
  • Apache OFBiz, the open source enterprise resource planning (ERP) system, uses Groovy.
  • SmartThings, an open platform for smart homes and the consumer Internet of Things, uses a security-oriented subset of Groovy
  • Survata, a market research startup, uses Groovy and Grails.
  • Jenkins, a platform for continuous integration. With version 2, Jenkins includes a Pipeline plugin that allows for build instructions to be written in Groovy.
  • IDE support

    Many integrated development environments (IDEs) and text editors support Groovy:

  • Eclipse, through Groovy-Eclipse
  • Emacs, using the groovy-emacs-mode project's groovy-mode.
  • IntelliJ IDEA, Community Edition, Grails/Griffon in the Ultimate Edition only
  • NetBeans, since version 6.5
  • TextMate
  • DataMelt Java IDE
  • Sublime Text 2, a cross platform text editor
  • JDeveloper, for use with Oracle ADF
  • jEdit, an advanced text editor for the Java platform
  • Kate, an advanced text editor for KDE supports Groovy and over 200 other file formats
  • Notepad++, an advanced text editor for Microsoft Windows
  • Android Studio, IDE used for making Android apps
  • Atom IDE
  • References

    Groovy (programming language) Wikipedia