Notice: Use of undefined constant ‘file - assumed '‘file' in /home/jpalio/vhosts/jpaliowikien.torn.com.pl/LocalSettings.php on line 154

Notice: Use of undefined constant bi’ - assumed 'bi’' in /home/jpalio/vhosts/jpaliowikien.torn.com.pl/LocalSettings.php on line 154
Groovy:Home - Jpaliowiki EN

Groovy:Home

From Jpaliowiki EN

Jump to: navigation, search

Contents

About the language

Features of the language:

  • a script language inspired by Python, Ruby and Smalltalk, with the syntax similar to that of the Java language
  • the ability to use the standard Java library and jPALIO modules library
  • one-time compilation to bytecode when first initiated

Variables

  • Variables are created when they are assigned
  • Data types are identical to those of Java
String str = "Hello"   // str is a String type variable
str = 5                // casting Long -> String
Long x = 10            // x is a Long type variable
x = "five"             // ERROR! casting is not possible
  • Variables do not have to be of a specific data type - when a value is assigned to them there is an automatic data type change
x = "Hello" // x is the String type variable
y = 8       // y is the Integer type variable
x = 5       // z becomes the Integer type variable
y = "eight" // y becomes the String type variable
  • Variables that are not of a specific data type can be preceded with the def keyword - such variables are visible only in the block, in which they were defined
a = "a"
def b = "b"
try
{
 c = "c"
 def d = "d"
 println a // list the value of variable a
 println b // list the value of variable b
 println c // list the value of variable c
 println d // list the value of variable d 
}
println a // list the value of variable a
println b // list the value of variable b
println c // list the value of variable c
println d // error - variable d is not visible outside the block, in which it was defined
  • Links are available globally in the whole script
  • Character strings can be placed either in single or double quotation marks - character strings in single quotation marks are not interpreted; character strings in double quotation marks are interpreted in such a way that all occurrences of the structure ${variable or expression} in those character strings are replaced by values of respective variables or expressions.
  • Character strings can spread over many lines - the beginning and the end of such character string can be either 3 single or 3 double quotation marks
text = """
first line
second line
third line
"""
  • The '\' character at the end of a multi-line character string means the lack of the end-of-line character, so
text = """\
1\
2
3\
4\
"""

is equivalent to

"""12
34"""

Data types

List

The list is an ordered collection of data. Lists are defined as strings of values in square brackets. The indexing operator is available for lists. List elements are indexed from 0

l = [-1, 2, 15]  // create a list of 3 values
println l.get(1) // retrieve and print the second list elements (2)
println l[2]     // retrieve and print the third list elements using the indexing operator (15)
println l.size() // retrieve and print the number of list elements (3)

Creating an empty list

l = []

Adding elements to the list

l = []        // empty list
l.add("five") // add the string "five" to the list
              // from now on l = ["five"]
l[2] = 8      // add the number 8 to the list using the indexing operator
              // from now on l = ["five", null, 8]

Map

A map is a collection of key-value pairs. Maps are defined as pair strings in square brackets. Each pair contains a key and a value, separated by a colon. The indexing operator is available for maps.

m = ["dog" : "brown", "cat" : "gray", "id": 512]
println m.get("dog") // retrieve and print the value for the key "dog" (brown)
println m["id"]      // retrieve and print the value for the key "id" (512)
println m.cat        // retrieve and print the value for the key "cat" (gray)
println m.size()     // retrieve and print the number of map elements (3)

Creating an empty map

m = [:]

Adding elements to the map

m = [:]           // empty map
m.put("three", 3) // add a pair with the key "three" and the value "3" to the map
                  // from now on m = ["three" : 3]
m["seven"] = 7    // add a pair with the key "seven" and the value 7 to the map using the indexing operator
                  // from now on m = ["three" : 3, "seven" : 7]

Range

A range is a collections of sequential values. A range is a list's derivative type. The indexing operator is available for ranges.

Closed range

r = 5..8              // create a range that corresponds to the list of values [5, 6, 7, 8]
println r[1]          // retrieve and print the second range element (6)
println r.contains(5) // check and print if the range contains the value 5 (true)
println r.contains(8) // check and print if the range contains the value 8 (true)

Open range

r = 5..<8             // create a range  that corresponds to the list of values [5, 6, 7]
println r[1]          // retrieve and print the second range element (6)
println r.contains(5) // check and print if the range contains the value 5 (true)
println r.contains(8) // check and print if the range contains the value 8 (false)

Ranges can contain objects of any type that implement java.lang.Comparable

r = 'a'..'d'   // create a range that corresponds to the list of values [ 'a', 'b', 'c', 'd' ]
println r[1]   // etrieve and print the second range element ('b')

Closures

Closures are code fragments that can be used as regular variables. By default, closures take a single argument named it

sqr = { it * it } // definition of a closure that returns square of its call parameter
println sqr(3)    // call a closure with the parameter 3 and print the value (9)

It is also possible to name closure arguments. The syntax is as follows

cls = { arg1, arg2 -> }

Closures can be passed on as function call parameters

l = [1, 2, 3]          // create a list of 3 values [1, 2, 3]
println l.collect(sqr) // call to the collect function with the squares of the list 1 elements and print the result ([1, 4, 9])
l.each({ x ->          // iterate cubes of the list 1 elements using a named closure argument and print their values (1, 4, 9)
  xxx = x * x * x
  print xxx
})

Control instructions

Conditional instruction - if

Syntax of the if instruction is know from the Java language

 if (condition)
 {
   operations executed if the condition is met
 }
 if (condition)
 {
   operations executed if the condition is met
 }
 else
 {
   operations executed if the condition is not met
 }

There is also a conditional operator

y = 5
x = (y > 1) ? "GOOD" : "BAD"

Conditional instruction - switch

The switch instruction is able to handle values of any type: class names (matching if the variable is an instance of a specific class), regular expressions (matching if the variable matches s regular expression), collections (matching if the variable exists in a collection - a list, a map or a range), values (matching if the variable has a specific value).

x = 1.23
result = ""
switch (x) {
    case "foo":
        result = "foo"
        // continue
    case "bar":
        result += "bar"
        break
    case [4, 5, 6, 'inList']:
        result = "list"
        break
    case 12..30:
        result = "range"
        break
    case Integer:
        result = "integer"
        break
    case Number:
        result = "number"
        break
    default:
        result = "default"
}

Loop - for

There are several versions of the for loop

  • range iteration
x = 0
for ( i in 0..9 ) { x += i }
  • list iteration
x = 0
for ( i in [0, 1, 2, 3, 4] ) { x += i }
  • array iteration
x = 0
for ( i in (0..4).toArray() ) { x += i }
  • map iteration
x = 0
for ( e in ['abc':1, 'def':2, 'xyz':3] ) { x += e.value }
  • text characters iteration
list = []
for (c in "abc") { list.add(c) }

Loop - while

Syntax of the while loop is as follows

while (condition)
{
  operations executed as long as the condition is met
}

Loop - each

The each loop enables iteration by all elements of the collection

  • list iteration
stringList = ["java", "perl", "python", "ruby", "c#", "groovy", "jython", "prolog"];
stringList.each({ println "${it}"; })
  • map iteration
stringMap = [ "Sun" : "Sunday", "Mon" : "Monday", "Tue" : "Tuesday", "Wed" : "Wednesday", "Thu" : "Thursday", "Fri" : "Friday", "Sat" : "Saturday" ];
stringMap.each({ key, value -> println "${key} == ${value}" })

Exception handling

Exceptions are handled by the try-catch or try-catch-finally block

try 
{
  operations that can return exceptions
} 
catch (e) 
{
  exception handling operations
} 
try 
{
  operations that can return exceptions
} 
catch (e) 
{
  exception handling operations
} 
finally 
{
  operations that are always executed, regardless of any exception
}

Regular expressions

Matching operator ==~ returns true if the whole character string on the operator's left side matches the regular expression on the operator's right side

"potatoe" ==~ /potatoe/

Operators to create regular expressions

x?     - 0 or 1 occurrence of x (the longest possible match)
x*     - 0 or more occurrences of x (the longest possible match)
x+     - 1 or more occurrences of x (the longest possible match)
x??    - 0 or 1 occurrence of x (the shortest possible match)
x*?    - 0 or more occurrences of x (the shortest possible match)
x+?    - 1 or more occurrences of x (the shortest possible match)
x|y    - occurrence of x or y
.      - any character
[xyz]  - any of the characters x, y, z
[^xyz] - any character except for x, y, z
[x-z]  - any character from the range from x to z
^      - beginning of a text line
$      - end of a text line
(   )  - grouping of a part of the regular expression (numbered group)
(?: )  - grouping of a part of the regular expression (non-numbered group)
\?     - character ?
\*     - character *
\+     - character +
\|     - character |
\.     - character .
\[     - character [
\]     - character ]
\-     - character -
\^     - character ^
\$     - characterk $
\)     - characterk )
\(     - character (
\:     - character :

Regular expressions can be used to retrieve from character strings data that matches an expression or a fragment of an expression. For this you can use matcher (operator =~). Unlike ==~ that requires matching of a regular expression to the whole character string, the operator =~ returns all matches of a regular expression in the character string

data = "Liverpool, England: 53d 25m 0s 3d 0m 0s"
regexp = /([a-zA-Z]+), ([a-zA-Z]+): ([0-9]+). ([0-9]+). ([0-9]+). ([0-9]+). ([0-9]+). ([0-9]+)./
match = (data =~ regexp)

The match variable is a two-dimensional array. Its first dimension corresponds to subsequent matches of a regular expression with the character string and the second dimension corresponds to subsequent groups from the regular expression. In the above example the regular expression will be matched once, so

match[0] ==  ["Liverpool, England: 53d 25m 0s N 3d 0m 0s", "Liverpool", "England", "53", "25", "0", "3", "0", "0"]

and

match[0][0] = "Liverpool, England: 53d 25m 0s N 3d 0m 0s"
match[0][1] = "Liverpool"
match[0][2] = "England"
...

To check if a match was found we can use the method

match.matches()

To determine the number of matches we can use the method

match.getCount()

To replace fragments of a character string that match the expression with another character string we can use functions replaceFirst() and replaceAll()

text = "Anna has a cat. Anna has a dog.";
match = (text =~ /Anna/);
text = match.replaceAll("Hannah");

Regular expressions can also be used in case of multi-line character strings, e.g. changing the first letter in each of the lines to uppercase

before = """
apple
orange
banana
"""

after = before.replaceAll(/(?m)^\w+/,{it[0].toUpperCase() + it[1..-1]})

Differences as compared to Java

  • operator == means difference for all types - it is equivalent to the equals() method
  • the is() method is used to check equality
foo.is(bar);
  • the is() method does not work with null, but then we can use the operator ==
foo == null
  • "in" is a keyword
  • the array declaration requires the following record:
int[] a = [1,2,3]
  • no for loop of the type:
for (i = 0; i < 10; i++) { ... }
  • the usage of a semicolon is optional; a semicolon is required if there are several expressions in the same line, e.g.
y = 5; x = y + 7

and in case of the usage of the instance initialization, e.g.

class Test 
{ 
  private final engine = new Engine(); 
  { engine.initialize() } 
}
  • the "return" keyword is optional
  • inside static methods you can use the "this" keyword, it then refers to THIS class
  • by default, methods and classes are public
  • there are no embedded classes; closures instead of embedded classes
  • the "throws" clause in method headers is ignored by the complier
  • in calls to methods parenthesis can be omitted if the method has at least one parameter and there is no ambiguity
println "Hello world"
  • The regular expression beginning and end character '/' can also be used as the character string beginning and end character
if ("cheese" == /cheese/) { println "TRUE"; } else { println "FALSE"; }

Documentation

Full documentation of the Groovy language is available at the following address

http://groovy.codehaus.org/
Personal tools