01
Einstieg
Hello World
Groovy ist Java-kompatibel, aber deutlich kompakter.
groovy
println "Hello, World!"Variablen
def für dynamische Typisierung, explizite Typen sind ebenfalls möglich.
groovy
def x = 10
def s = "hello"
int y = 20Closures
Closures sind Codeblöcke; 'it' ist der Standardparameter.
groovy
def square = { n -> n * n }
println square(5)
[1, 2, 3].each { println it }Strings
Doppelte Anführungszeichen erlauben ${}-Interpolation, einfache nicht.
groovy
def name = "World"
println "Hello, ${name}!"
println 'No interpolation'02
Datenstrukturen
Listen
<< hängt an eine Liste an; collect entspricht map.
groovy
def lst = [1, 2, 3]
lst << 4
lst.each { println it }
lst.collect { it * 2 }Maps
Maps verwenden das [:]-Literal; Zugriff per .property.
groovy
def m = [a: 1, b: 2]
m.c = 3
println m.a
m.each { k, v -> println "$k=$v" }Ranges
Ranges sind Objekte erster Klasse.
groovy
def r = 1..5
r.each { println it }
(1..10).findAll { it % 2 == 0 }03
Fortgeschritten
Klassen
Klassen ähneln Java, aber mit weniger Boilerplate.
groovy
class Person {
String name
int age
}
def p = new Person(name: "Alice", age: 30)
println p.nameGStrings
GStrings unterstützen beliebige Ausdrücke in ${}.
groovy
def items = [1, 2, 3]
println "Items: ${items.join(", ")}"
println "Sum: ${items.sum()}"Was this helpful?