Groovy Notes

 Groovy is a great mix of dynamic flavor, while still  being able to use types. It is one of few languages  that sport optional typing, that is, the flexibility  to provide type information if we want to and leave  type information aside when we don't want to.

Closure in Groovy is a block of code that can be assigned to  a reference or passed around just like any other variable.  The concept is known as lambda in many other languages,  including Java 8 or function pointers.

1.) Hello World program 

 def cl1 = {
     println "hello world!"
}

cl1.call()

it prints the following:

hello world!


2.) As closures are like methods, they can also accept parameters:


example 1:

def cl2 = { n ->
    println "value of param : $n"
}
cl2.call(101)
It prints the following:

value of param : 101

example 2:
3.times(cl2)
It prints the following:

value of param : 0
value of param : 1
value of param : 2

We can also inline the block and pass it directly to a method:

3.times { println it * it }

It prints the following:

0
1
4


There is a special variable called it, which is available in the blocks
scope if the closure doesn't define its parameter.

Data structures

List:

1.) def aList = []
println aList.getClass()
It prints the following:

class java.util.ArrayList

2.) def anotherList = ['a','b','c']

   anotherList[1] will give us b.

3.)adding , subtractign to a list
        sample : 
        def list = [10, 20, 30] + [40, 50]
         list << 60;
         list -= [20,30,40]
        list.each(){println it}
        
        result : 10 50 60
     

Set:


1.)
def aSet = [1,2,3] as Set
println aSet.class

This will print the following:

class java.util.LinkedHashSet

2.)
TreeSet anotherSet = [1,2,3]
println anotherSet.class
This prints the following:

class java.util.TreeSet

3.)
aSet << 4
aSet << 3
println aSet
This prints the following:

[1, 2, 3, 4]
We don't see the entry 4 twice as the collection is
a set implementation, which by definition eliminates
duplicates.

Map:


def a = [:]
The implementation chosen by default is java.util.LinkedHashMap, which preserves the insertion order:

def tool = [version:'2.8', name:'Gradle', platform:'all']

Note that the keys are not string literals, but they get
automatically converted to a string:

println tool.name
println tool["version"]
println tool.get("platform")

Gradle
2.8
all

We can put and update data in map using the subscript and dot operator and, of course, the good old put():


Groovy Methods:


int sum(int a, int b) {
  return a + b;
}

The preceding method can be succinctly rewritten as follows:

def sum(a, b) {
  a + b //evaluation of the last expression is automatically returned by a method.
}

calling method :

sum(1,2)
sum 1, 2

Method with Map Paramters:

def method(Map options) {
    def a = options.a ?: 10
    def b = options.b ?: 20
}


method([a:10,b:20])
method(a:10, b:20)

method b:30, a:40
method b:30

Methods with varags:

def sumSquares(...numbers) {
    numbers.collect{ it * it }.sum()
}
sumSquares 1, 2, 3

Methods with closure params:

Closures are important and, hence, Groovy has a special syntax closures if the closure is the last parameter of a method signature:

def myMethod (param, cls) {
    ...
}
Then, this method can be called as follows:

myMethod(1,{ ... })
myMethod 2, {... }
myMethod(3) {...}

Out of these, the third one is the special syntactical support in which the parenthesis just wraps the other parameters, while the closure is written outside the parenthesis, as if it were a method body.

Classes:

Classes are public by default. They can inherit from other classes using extends or implementing
interfaces using implements.

class Person {
  def name, age
}

Constructors:

def person = new Person(name:"John Doe", age:35)


Properties
Groovy has language-level support for properties

public accessors and mutators (getters and setters) are generated automatically.


println person.age
person.age = 36
println person.age

35
36

We can provide our own getters and/or setter for the desired fields

Miscellaneous:


apply plugin: 'java'
project.apply([plugin: 'java'])

Comments

Popular posts from this blog

Palindrome program in Java using BufferedReader

OOPS: Decomposition and Abstraction