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.groovyprintln "test" // same as println ("test")
void showSum(int a, int b) {
println a + b
}
showSum 3, 4 // same as showSum (3,4) Outputtest 7
Parentheses are required for method calls without parameters:
src/OptionalParentheses2.groovyimport java.time.LocalDateTime
void showTimeNow() {
println LocalDateTime.now()
}
showTimeNow() //good
showTimeNow //not good
Output2018-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.groovyprintln 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.groovyprintln "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())
Outputpublic
Example ProjectDependencies and Technologies Used: |