Learn Groovy In Minutes

pranit sawant
4 min readSep 25, 2017

--

Learning a new language generally involves lots of time and energy because of various program elements like Syntax, Operators, Control Structures etc. have to be remembered. But, learning groovy doesn’t consume much time as the Language syntax resembles same as the java.

Excitement at its peak to learn powerful, optionally typed and dynamic language, which offers scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional Programming. Simply follow the steps below and you will definitely learn basics of groovy.

Set yourself up

  1. Install SDKMAN — http://sdkman.io/
  2. Install Groovy: sdk install groovy
  3. Start the groovy console by typing: groovyConsole

Compile and Learn ;)

Commenting

// Single line comment start with two forward slashes
/*
Multi line comments look like this.
*/

Hello World!

println "Hello World!"

Variables

def x = 1println xx = new java.util.Date()println xx = -3.14println xx = "Groovy!"println x

Collection and Map

Groovy Beans

GroovyBeans are JavaBeans but using a much simpler syntax

When Groovy is compiled to bytecode, the following rules are used.

  • If the name is declared with an access modifier (public, private or
    protected) then a field is generated.
  • A name declared with no access modifier generates a private field with
    public getter and setter (i.e. a property).
  • If a property is declared final the private field is created final and no
    setter is generated.
  • You can declare a property and also declare your own getter or setter.
  • You can declare a property and a field of the same name, the property will
    use that field then.
  • If you want a private or protected property you have to provide your own
    getter and setter which must be declared private or protected.
  • If you access a property from within the class the property is defined in
    at compile time with implicit or explicit this (for example this.foo, or
    simply foo), Groovy will access the field directly instead of going though
    the getter and setter.
  • If you access a property that does not exist using the explicit or
    implicit foo, then Groovy will access the property through the meta class,
    which may fail at runtime.
class Foo {
// read only property
final String name = "Pranit"
// read only property with public getter and protected setter
String language
protected void setLanguage(String language) { this.language = language }
// dynamically typed property
def lastName
}
/*
Logical Branching and Looping
*/
//Groovy supports the usual if — else syntax
def x = 3
if(x==1) {
println “One”
} else if(x==2) {
println “Two”
} else {
println “X greater than Two”
}
//Groovy also supports the ternary operator:
def y = 10
def x = (y > 1) ? “worked” : “failed”
assert x == “worked”
//Groovy supports ‘The Elvis Operator’ too!
//Instead of using the ternary operator:
displayName = user.name ? user.name : ‘Anonymous’//We can write it:
displayName = user.name ?: ‘Anonymous’

For loop

Operators

Operator Overloading for a list of the common operators that Groovy supports:
Helpful groovy operators
//Spread operator: invoke an action on all items of an aggregate object.
def technologies = ['Groovy','Grails','Gradle']
technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() }
//Safe navigation operator: used to avoid a NullPointerException.
def user = User.get(1)
def username = user?.username

Closures

A Groovy Closure is like a “code block” or a method pointer. It is a piece of
code that is defined and then executed at a later point.

Check more about closure, click here.

Expando

The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class.

def user = new Expando(name:"Pranit")
assert 'Pranit' == user.name
user.lastName = 'Sawant'
assert 'Sawant' == user.lastName
user.showInfo = { out ->
out << "Name: $name"
out << ", Last name: $lastName"
}
def sw = new StringWriter()
println user.showInfo(sw)
/*
Metaprogramming (MOP)
*/
//Using ExpandoMetaClass to add behaviour
String.metaClass.testAdd = {
println “we added this”
}
String x = "test"
x?.testAdd()
//Intercepting method calls
class Test implements GroovyInterceptable {
def sum(Integer x, Integer y) { x + y }
def invokeMethod(String name, args) {
System.out.println “Invoke method $name with args: $args”
}
}
def test = new Test()
test?.sum(2,3)
test?.multiply(2,3)
//Groovy supports propertyMissing for dealing with property resolution attempts.
class Foo {
def propertyMissing(String name) { name }
}
def f = new Foo()
assertEquals "boo", f.boo/*
TypeChecked and CompileStatic
Groovy, by nature, is and will always be a dynamic language but it supports
typechecked and compilestatic
More info: http://www.infoq.com/articles/new-groovy-20
*/
//TypeChecked
import groovy.transform.TypeChecked
void testMethod() {}@TypeChecked
void test() {
testMeethod()
def name = "Pranit"println name}//Another example:
import groovy.transform.TypeChecked
@TypeChecked
Integer test() {
Integer num = "1"
Integer[] numbers = [1,2,3,4]Date date = numbers[1]return "Test"}//CompileStatic example:
import groovy.transform.CompileStatic
@CompileStatic
int sum(int x, int y) {
x + y
}
assert sum(2,5) == 7

Explore more about Groovy here are some references

--

--