Close

Groovy - Optional Features

[Last Updated: Dec 3, 2018]

To increase readability and productivity, Groovy makes various features optional (same features are not optional in Java).

Optional Parentheses

Method calls can omit the parentheses:

src/OptionalParentheses.groovy

println "test" // same as println ("test")

void showSum(int a, int b) {
    println a + b
}

showSum 3, 4 // same as showSum (3,4)

Output

test
7

Parentheses are required for method calls without parameters:

src/OptionalParentheses2.groovy

import java.time.LocalDateTime

void showTimeNow() {
    println LocalDateTime.now()
}

showTimeNow() //good
showTimeNow //not good



Output

2018-11-08T13:04:07.736202
Caught: groovy.lang.MissingPropertyException: No such property: showTimeNow for class: OptionalParentheses2
groovy.lang.MissingPropertyException: No such property: showTimeNow for class: OptionalParentheses2
at OptionalParentheses2.run(OptionalParentheses2.groovy:8)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Parentheses are also required for ambiguous method calls:

src/OptionalParentheses3.groovy

println Math.pow(3, 4) //good
println Math.pow 3 , 4 //not good
println(Math.pow 3, 4)//not good

Optional semicolons

semicolons at the end of the line can be omitted, if the line contains only a single statement:

src/OptionalSemiColons.groovy

println "sum" //good
println 1 + 1 //good
println "sum" println 1 + 1 //not good

Optional public keyword

import java.lang.reflect.Modifier

void testMethod() {
}

//using reflection
println Modifier.toString(this.getClass()
                              .getDeclaredMethod("testMethod")
                              .getModifiers())

Output

public

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy Optional features Select All Download
  • groovy-optional-features
    • src
      • OptionalParentheses.groovy

    See Also