Groovy basic language

Semicolons

The use of semicolons ( ; ) in Groovy is completely optional . The only time a semicolon has to be used, is when multiple function calls are placed on the same line

print ("Hello")
print (" world!")
//Above statement print "Hello world!"

Data type declaration

When creating an object, it’s type doesn’t have to be defined explicitly. By using the def-keyword, Groovy will automatically detect what object type has to be used

word=" Hello World!"
print word.class //class java.lang.String
def number=10
print number.class //class java.lang.Integer

Although optional, Groovy still enables object types to be declared explicitly. This might be useful in situations where only one data type is allowed.

Groovy String

The Groovy String (Also called “GString”) allows for any type of logic to be integrated in the String definition. This can be done with the dollar symbol ( $ ) and (optional) braces ( { } ). The difference between a String and a GString is automatically recognized by Groovy.

word="Hello World!"
name="World"
gstring="Hello $ (name)!"

Embedded quotes

Groovy has a nice way of working with Strings. In Java, a single quote would represent the primitive type char. In Groovy, anything that is surrounded by either single or double quotes is converted to a String. This is very useful when working with Strings that contain quotes. As this example will show, Strings with doubles quotes in it can be surrounded with single quotes en vice versa. To escape a quote, a backslash is used

singlequote="Hello 'World'"
print singlequote  //It print  Hello 'World'
doublequote='Hello "World";
print doublequote   //It print  Hello "World"
escapequote="Hello \"World\""
print escapequote  //It print Hello "World"

Collections

Groovy acknowledges three different types of collections. The first two, Lists and Maps, are no different from the ones used in Java. Lists use a null-based index to retrieve items, whereas Maps use a unique key to find an item. Ranges however, are more or less unique to dynamic languages.

A simple example of a list in Groovy is:

def romanNumber={,'''I",'II','III','IV','V','VI','VII'}

The first entry being zero in Roman, which is the word ‘nulla’ and doesn’t have a notation. A map is created by assigning values to a corresponding key, like such:\

def http={
100: 'CONTINUE',
200:'OK',
400: 'BAD REQUEST'
}

Although ranges don’t appear in the standard Java libraries, most programmers have an intuitive idea of what a range is. Effectively, a range defines a start and an end point, with a notion of how to move from the start to the end point. Groovy provides literals to support for ranges, along with other language features such as the for statement, which understands ranges.

Declaring a range is easy:

def a=1..10

Declaring Classes

Classes are the cornerstone of object-oriented programming, because they define the blueprint from which objects are drawn.

The code below contains a simple Groovy class named Book, which has an instance variable title, a constructor that sets the title, and a getter method for the title.

By default, all methods are public and therefore access modifiers are excluded.

class Book {
privaye String name
Book(String vName){
name=vName
}
String getName(){
return this.name
}
}

 Return Statements

The last line of a method in Groovy is automatically the return statement. For this reason, an explicit return statement can be left out

def getWorld()
{
"World"
}
print getWorld() // print World

To return a value that is not on the last line, the return statement has to be declared explicitly.

def getEmployee(String name)
{
if(name!=null)
return "Hello $name!"
else
return "Hello Guest!"
}
print getEmployee("SAM") //print Hello SAM
print getEmployee() //print Hello Guest!
[/code]

 

Boolean

Every object in Groovy has a Boolean representation, which value depends on it's content and type. A String for instance, will return true if populated and false if empty. This allows for quick “truth”-checking, and reduces the amount of code involved.

boolean

Operator overloading

Operator overloading allows the default use of operators to be overridden to enable a more intuitive approach for common methods. The way Groovy implements this, can be seen in the following table.

OperatorOverloding

Loops

Because of Groovy's origin in Java, it natively supports both the for- and while-loop. Groovy's for-each loops though, have a slight difference in syntax when compared with their Java equivalents.

A Java for-each loop looks like this:

for (vatiable : iterable){}

Groovy's counterpart however, uses the keyword 'in' instead of Java's colon

for (variable in iterable){}

Groovy has some special capabilities for collections, among which the range. Groovy provides some extra looping techniques that can be used in collaboration with these. The each-method can be used on collections, and executes a given closure for each of the items in the list.

('A'..'Z').each(print it) //ABCDEFGHIJKLMNOPQRSTUVWXYZ

 

The eachWithIndex does essentially the same, but keeps an numbered index that can be accessed from within the closure.

('A'..'Z').eachWithIndex(obj,it->println "${i+1}.${obj}"}
/**
1.A
2.B
...........
25.Y
26.Z
*/

 

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s