Page tree
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 17 Current »

This document is a useful summary for people who don't know the Groovy language.
We list here most of the Groovy code that we use inside the Cytomine code. 
This is not all the Groovy rules, this is the main used rules inside Cytomine (non-exhaustive!!!). 

Java wayGroovy wayNote
statement;
statement

 

 

 

 

; is not mandatory at the end of a statement.
return var;
var
If method is not void and no return statement,
Groovy return the last exec statement in a function 
Object var
int var
List var 
int foo(int var) {
	return var;
}
def var
int number
 
def foo(def var) {
	var
}
Java way is OK in Groovy too
class User {
    private String name;

    public String getName() {...}
    public void setName(String name) {...} 
 
}
class User {
    private String name;

    //getter/setter auto generated
} 
 
Getter and setter auto generated for private members.

 

 

def object = ...
object.newField = "test"

 

 

You can add new field or new method to an object at Runtime.
java.io.*
java.lang.*
java.math.BigDecimal
java.math.BigInteger
java.net.*
java.util.*
groovy.lang.*
groovy.util.*

 

Groovy auto import all these packages.

 

try {
	methodMayThrowException()
} catch(...) {...}
methodMayThrowException()
 
String s = "hello " + name 
String s = "hello " + user.getName(); 
String s = "hello $name"
String s = "hello ${user.getName()} 
GStrings
List<String> list = new list<String>();
def list = []
def listNotEmpty = [1,2,3] 
Syntacttic sugar for lists.
Map<Long,String> map = new Map<Long, String>();


String x = map.get(2) 
def map = [:]
def mapNotEmpty = [1:"a",2:"b",3:"c"]

def x = map[2] //or map.get(2)
Syntactic sugar for maps.
for(String item : list) {
     doSomething(item);
}
list.each {
     doSomething(it);
}

Apply function on each element of a list.

By default, the current item in each{} is it.
You can change this by:

.each {item -> ...}

You can get the index (current position in list):

.eachWithIndex {item, i -> ...}
List<User> users = ...
List<String> names = ...

for(User user : users) {
     names.add(user.getName());
}
def names = users.collect{it.getName())
Build a list from anohter one.
System.out.println(...);
println(...)
 
  • No labels