Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Java wayGroovy wayNote
Code Block
languagejava
statement;
Code Block
languagegroovy
statement

 

 

 

 

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

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

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

 

 

Code Block
languagegroovy
def object = ...
object.newField = "test"

 

 

You can add new field or new method to an object at Runtime.

 

 

 

Code Block
languagejava
java.io.*
java.lang.*
java.math.BigDecimal
java.math.BigInteger
java.net.*
java.util.*
groovy.lang.*
groovy.util.*

 

 

 

 

Groovy auto import all these packages.

 

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


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

def x = map[2] //or map.get(2)
Syntactic sugar for maps.
Code Block
languagejava
for(String item : list) {
     doSomething(item);
}
Code Block
languagegroovy
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:

Code Block
.each {item -> ...}

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

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

for(User user : users) {
     names.add(user.getName());
}
Code Block
languagegroovy
def names = users.collect{it.getName())
Build a list from anohter one.
Code Block
languagejava
System.out.println(...);
Code Block
languagegroovy
println(...)