Last active
August 29, 2015 14:10
-
-
Save aceakash/14e5d9fe31db5da8452e to your computer and use it in GitHub Desktop.
Groovy cheat sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Execute shell command and retrieve output with 'execute' | |
"groovy -v".execute().text | |
//--------------------------------------- | |
// repeating something a fixed number of times with 'times' | |
// accessing the only value in a closure with 'it' | |
3.times { println "Hello! This is $it" } | |
//--------------------------------------- | |
// ranges | |
(0..2).each { println it } | |
(0..<2).each { println it } | |
//--------------------------------------- | |
// safe-navigation operator - ?. | |
def foo(str) { str?.reverse() } | |
foo('hello') // 'olleh' | |
foo(null) // null | |
//--------------------------------------- | |
def listOfArgs(a, b, c) { [a, b, c] } | |
// all named args are combined into a map as the first param | |
listOfArgs(x: 10, y: 99, 3, 'ok') // [[x:10, y:99], 3, ok] | |
// even if they are all over the place | |
listOfArgs(x: 10, 3, y: 99, 'ok', z: -2) // [[x:10, y:99, z:-2], 3, ok] | |
//--------------------------------------- | |
// methods can have optional params at the end | |
def log(x, base=10) { Math.log(x) / Math.log(10) } | |
log(1024) // 3.0102999566398116 | |
log(1024, 2) // 10.0 | |
// -------------------------------------- | |
// methods can have an optional trailing array param | |
def sendText(msg, String[] friends) { | |
println "Sending '$msg' to $friends" | |
} | |
sendText('Pizza tonight?') // Sending 'Pizza tonight?' to [] | |
sendText('Pizza tonight?', 'Bruce') // Sending 'Pizza tonight?' to [Bruce] | |
sendText('Pizza tonight?', 'Bruce', 'Clark') // Sending 'Pizza tonight?' to [Bruce, Clark] | |
// -------------------------------------- | |
// an array can be split-assigned to multiple variables | |
(x, y) = [6, 7] | |
println x // 6 | |
println y // 7 | |
// this makes swapping easy | |
(x, y) = [y, x] | |
println x // 6 | |
println y // 7 | |
// this also lets methods return multiple values | |
def splitName(fullName) { fullName.split(' ') } | |
(firstName, lastName) = splitName('Steve Rogers') | |
println firstName // Steve | |
println lastName // Rogers | |
// specifying variable types while assigning | |
def (String cat, String mouse) = ['Tom', 'Jerry'] | |
println "$cat and $mouse" // Tom and Jerry | |
// -------------------------------------- | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment