Groovy (programming language)
   HOME

TheInfoList



OR:

Apache Groovy is a
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
-syntax-compatible
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
for the Java platform. It is both a static and
dynamic Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dyn ...
language with features similar to those of Python,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
, and Smalltalk. It can be used as both a
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
and a
scripting language A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled. A scripting ...
for the Java Platform, is compiled to Java virtual machine (JVM)
bytecode Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (norma ...
, and interoperates seamlessly with other Java code and libraries. Groovy uses a curly-bracket syntax similar to Java's. Groovy supports closures, multiline strings, and expressions embedded in strings. Much of Groovy's power lies in its AST transformations, triggered through annotations. Groovy 1.0 was released on January 2, 2007, and Groovy 2.0 in July, 2012. Since version 2, Groovy can be compiled statically, offering
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
and performance near that of Java. Groovy 2.4 was the last major release under
Pivotal Software Pivotal Software, Inc. was an American multinational software and services company based in San Francisco that provided cloud platform hosting and consulting services. Since December 2019, Pivotal has been part of VMware. History Pivotal ...
's sponsorship which ended in March 2015. Groovy has since changed its governance structure to a Project Management Committee in
the Apache Software Foundation The Apache Software Foundation (ASF) is an American nonprofit corporation (classified as a 501(c)(3) organization in the United States) to support a number of open source software projects. The ASF was formed from a group of developers of the A ...
.


History

James Strachan first talked about the development of Groovy on his blog in August 2003. In March 2004, Groovy was submitted to the JCP as JSR 241 and accepted by ballot. 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 Spring (previously known as SpringSource) was the company created by the founders of the Spring Framework (a programming model for enterprise Java applications) to support and develop Spring and related projects. Originally incorporated as Inte ...
acquired the Groovy and Grails company (G2One). In August 2009 VMware acquired SpringSource. In April 2012, after eight years of inactivity, the Spec Lead changed the status of JSR 241 to dormant. 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". On July 2, 2012, Groovy 2.0 was released, which, among other new features, added static compiling and
static type checking In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer prog ...
. When the
Pivotal Software Pivotal Software, Inc. was an American multinational software and services company based in San Francisco that provided cloud platform hosting and consulting services. Since December 2019, Pivotal has been part of VMware. History Pivotal ...
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 became 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.König 2007, pg. 32 This makes it possible for Java programmers to learn Groovy gradually by starting with familiar Java syntax before acquiring more Groovy
programming idiom In computer programming, a programming idiom or code idiom is a group of code fragments sharing an equivalent semantic role, which recurs frequently across software projects often expressing a special feature of a recurring construct in one or ...
s. Groovy features not available in Java include both static and
dynamic Dynamics (from Greek δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to: Physics and engineering * Dynamics (mechanics) ** Aerodynamics, the study of the motion of air ** Analytical dyn ...
typing (with the keyword def), operator overloading, native syntax for lists and associative arrays (maps), native support for regular expressions, polymorphic iteration, string interpolation, added helper methods, and the
safe navigation operator In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation operator) is a binary operator that returns null if its first argument is null; ...
?. to check automatically for
null pointer In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object. Programs routinely use null pointers to represent conditions such as the end of a list of unknown leng ...
s (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 the invokedynamic instruction introduced in Java 7. Groovy provides native support for various markup languages such as
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. T ...
and
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaS ...
, 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 Script may refer to: Writing systems * Script, a distinctive writing system, based on a repertoire of specific elements or symbols, or that repertoire * Script (styles of handwriting) ** Script typeface, a typeface with characteristics of ha ...
, 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 Python and Ruby). This occurs under the hood, and the compiled version is not saved as an artifact of the process.König 2007, pp. 37-8


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.König 2007, pp. 38-9 class AGroovyBean def myGroovyBean = new AGroovyBean() myGroovyBean.setColor('baby blue') assert myGroovyBean.getColor()

'baby blue' myGroovyBean.color = 'pewter' assert myGroovyBean.color

'pewter'
Groovy offers simple, consistent syntax for handling ''lists'' and ''maps'', reminiscent of Java's ''array'' syntax.König 2007, pp. 41-3 def movieList =
Dersu Uzala', 'Ran', 'Seven Samurai' Dersu is a small village located in the Primorsky Krai, in the Far Eastern Federal District of Russia. It is populated primarily by Old Believers Old Believers or Old Ritualists, ''starovery'' or ''staroobryadtsy'' are Eastern Orthodox Christian ...
// Looks like an array, but is a list assert movieList

'Seven Samurai' movieList = 'Casablanca' // Adds an element to the list assert movieList.size()

4 def monthMap = 'January' : 31, 'February' : 28, 'March' : 31 // Declares a map assert monthMap March'

31 // Accesses an entry monthMap April'= 30 // Adds an entry to the map assert monthMap.size()

4


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: Number.metaClass assert 9.sqrt()

3 assert 4.sqrt()

2
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: enum Color String.metaClass.getProperty = assert "WHITE".hex

"#FFFFFF" assert "BLUE".hex

"#0000FF" assert "BLACK".hex

"#000000" assert "GREEN".hex

null
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 take(coffee).with(sugar, milk).and(liquor) can be written as take coffee with sugar, milk and liquor enabling the development of domain-specific languages (DSLs) that look like plain English.


Functional programming

Although Groovy is mostly an object-oriented language, it also offers
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions tha ...
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 that have not been explicitly passed as a parameter to it, but exist in its declaration context, partial application (that 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: list = , 2, 3, 4, 5, 6, 7, 8, 9 /* * Non-zero numbers are coerced to true, so when it % 2

0 (even), it is false. * The type of the implicit "it" parameter can be inferred as an Integer by the IDE. * It could also be written as: * list.findAll * list.findAll */ def odds = list.findAll assert odds

, 3, 5, 7, 9
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: // This block of code contains expressions without reference to an implementation def operations = /* * This class will handle the operations that can be used in the closure above. Another class * could be declared having the same methods, but using, for example, webservice operations * in the calculations. */ class Expression // Here is defined who is going to respond the expressions in the block of code above. operations.delegate = new Expression() operations()


Curry

Usually called '' partial application'',"Does groovy call partial application 'currying'
, 10 Aug 2013
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. def joinTwoWordsWithSymbol = assert joinTwoWordsWithSymbol('#', 'Hello', 'World')

'Hello#World' def concatWords = joinTwoWordsWithSymbol.curry(' ') assert concatWords('Hello', 'World')

'Hello World' def prependHello = concatWords.curry('Hello') //def prependHello = joinTwoWordsWithSymbol.curry(' ', 'Hello') assert prependHello('World')

'Hello World'
Curry can also be used in the reverse direction (fixing the last N arguments) using rcurry(). def power = def square = power.rcurry(2) def cube = power.rcurry(3) assert power(2, 2)

4 assert square(4)

16 assert cube(3)

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


JSON and XML processing

On JavaScript Object Notation ( JSON) and XML processing, Groovy employs the Builder pattern, making the production of the data structure less verbose. For example, the following XML: Java object oriented static Ruby functional, object oriented duck typing, dynamic Groovy functional, object oriented duck typing, dynamic, static can be generated via the following Groovy code: def writer = new StringWriter() def builder = new groovy.xml.MarkupBuilder(writer) builder.languages 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: def languages = new XmlSlurper().parseText writer.toString() // Here is employed Groovy's regex syntax for a matcher (=~) that will be coerced to a // boolean value: either true, if the value contains our string, or false otherwise. def functional = languages.language.findAll assert functional.collect

Groovy", "Ruby"


String interpolation

In Groovy, strings can be interpolated with variables and expressions by using GStrings: BigDecimal account = 10.0 def text = "The account shows currently a balance of $account" assert text

"The account shows currently a balance of 10.0"
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: BigDecimal minus = 4.0 text = "The account shows currently a balance of $" assert text

"The account shows currently a balance of 6.0" // Without the brackets to isolate the expression, this would result: text = "The account shows currently a balance of $account - minus" assert text

"The account shows currently a balance of 10.0 - minus"
Expression evaluation can be deferred by employing arrow syntax: BigDecimal tax = 0.15 text = "The account shows currently a balance of $" tax = 0.10 // The tax value was changed AFTER declaration of the GString. The expression // variables are bound only when the expression must actually be evaluated: assert text

"The account shows currently a balance of 9.000"


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: * Category and Mixin transformation * Immutable AST Macro * Newify transformation * Singleton transformation among others.


Traits

According to Groovy's documentation, " Traits are a structural construct of the language that allows: 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: trait FlyingAbility Then, it can be used like a normal interface using the keyword implements: class Bird implements FlyingAbility /* Adds the trait FlyingAbility to the Bird class capabilities */ def bird = new Bird() /* instantiate a new Bird */ assert bird.fly()

"I'm flying!" /* the Bird class automatically gets the behavior of the FlyingAbility trait */
Traits allow a wide range of abilities, from simple composition to testing.


Adoption

Notable examples of Groovy adoption include: * Adaptavist ScriptRunner, embeds a Groovy implementation to automate and extend Atlassian tools, in use by more than 20000 organisations around the world. *
Apache OFBiz Apache OFBiz is an open source enterprise resource planning (ERP) system. It provides a suite of enterprise applications that integrate and automate many of the business processes of an enterprise. OFBiz is an Apache Software Foundation top lev ...
, the open-source enterprise resource planning (ERP) system, uses Groovy. *
Eucalyptus ''Eucalyptus'' () is a genus of over seven hundred species of flowering trees, shrubs or mallees in the myrtle family, Myrtaceae. Along with several other genera in the tribe Eucalypteae, including '' Corymbia'', they are commonly known as ...
, a cloud management system, uses a significant amount of Groovy. * Gradle is a popular build automation tool using Groovy. *
LinkedIn LinkedIn () is an American business and employment-oriented online service that operates via websites and mobile apps. Launched on May 5, 2003, the platform is primarily used for professional networking and career development, and allows job se ...
uses Groovy and Grails for some of their subsystems. * LogicMonitor, a cloud-based monitoring platform, uses Groovy in script-based data sources. * Jenkins, a platform for continuous integration. With version 2, Jenkins includes a ''Pipeline'' plugin that allows for build instructions to be written in Groovy. *Liferay, uses groovy in their kaleo workflow * Sky.com uses Groovy and Grails to serve massive online media content. * SmartThings, an open platform for smart homes and the consumer Internet of Things, uses a security-oriented subset of Groovy *
SoapUI SoapUI is an open-source web service testing application for Simple Object Access Protocol (SOAP) and representational state transfers (REST). Its functionality covers web service inspection, invoking, development, simulation and mocking, fun ...
provides Groovy as a language for webservice tests development. * Survata, a market research startup, uses Groovy and Grails. * The European Patent Office (EPO) developed a
dataflow programming In computer programming, dataflow programming is a programming paradigm that models a program as a directed graph of the data flowing between operations, thus implementing dataflow principles and architecture. Dataflow programming languages share ...
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." * 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. * vCalc.com uses Groovy for all of the user defined mathematics in its math crowd-sourcing engine. * Wired.com uses Groovy and Grails for the Product Reviews standalone section of the website. * XWiki SAS uses Groovy as scripting language in their collaborative open-source product.


IDE support

Many
integrated development environment An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools ...
s (IDEs) and text editors support Groovy: *
Android Studio Android Studio is the official integrated development environment (IDE) for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. It is available for download on Win ...
, IDE used for making Android apps *
Atom Every atom is composed of a nucleus and one or more electrons bound to the nucleus. The nucleus is made of one or more protons and a number of neutrons. Only the most common variety of hydrogen has no neutrons. Every solid, liquid, gas, a ...
editor * Eclipse, through Groovy-Eclipse *
Emacs Emacs , originally named EMACS (an acronym for "Editor MACroS"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, ...
, using the groovy-emacs-mode project's groovy-mode. *
IntelliJ IDEA IntelliJ IDEA is an integrated development environment (IDE) written in Java for developing computer software written in Java, Kotlin, Groovy, and other JVM-based languages. It is developed by JetBrains (formerly known as IntelliJ) and is av ...
, Community Edition, Grails/Griffon in the Ultimate Edition only *
JDeveloper JDeveloper is a freeware IDE supplied by Oracle Corporation. It offers features for development in Java, XML, SQL and PL/SQL, HTML, JavaScript, BPEL and PHP. JDeveloper covers the full development lifecycle from design through coding, deb ...
, for use with
Oracle ADF In computing, Oracle Application Development Framework, usually called Oracle ADF, provides a Java framework for building enterprise applications. It provides visual and declarative approaches to Java EE development. It supports rapid application ...
* jEdit, an advanced text editor for the Java platform * Kate, an advanced text editor for KDE supports Groovy and over 200 other file formats * NetBeans, since version 6.5 *
Notepad++ Notepad++ is a text and source code editor for use with Microsoft Windows. It supports tabbed editing, which allows working with multiple open files in a single window. The product's name comes from the C postfix increment operator. Notepad ...
, an advanced text editor for
Microsoft Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for ...
*
Sublime Text Sublime Text is a shareware text and source code editor available for Windows, macOS, and Linux. It natively supports many programming languages and markup languages. Users can customize it with themes and expand its functionality with ...
, a cross platform text editor * TextMate * Visual Studio Code *
UltraEdit UltraEdit is a commercial text editor for Microsoft Windows, Linux and OS X created in 1994 by the founder of IDM Computer Solutions Inc., Ian D. Mead, and owned by Idera, Inc. since August 2021. The editor contains tools for programmers, includ ...
, general purpose program editor


Dialects

There is one alternative implementation of Groovy: * Grooscript converts Groovy code to
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
code. Although Grooscript has some limitations compared to Apache Groovy, it can use domain classes in both the server and the client. Plugin support for Grails version 3.0 is provided, as well as online code conversions.


See also

* Comparison of programming languages *
Griffon (framework) Griffon is an open source rich client platform framework which uses the Java, Apache Groovy, and/or Kotlin programming languages. Griffon is intended to be a high-productivity framework by rewarding use of the Model-View-Controller paradigm, prov ...
– a desktop framework *
Project Zero Project Zero is a team of security analysts employed by Google tasked with finding zero-day vulnerabilities. It was announced on 15 July 2014. History After finding a number of flaws in software used by many end-users while researching other ...
* Spock (testing framework)


References


Citations


Sources

* * * *


External links

* * {{Authority control Articles with example code Dynamically typed programming languages Java programming language family Java specification requests JVM programming languages Object-oriented programming languages Programming languages created in 2003 Scripting languages Software using the Apache license Programming languages Dynamic programming languages 2003 software Cross-platform free software Cross-platform software High-level programming languages