GROOVY AS A SCRIPTING LANGUAGECreatedby /JennStrater @jennstrater
WHAT'S GROOVY? Groovyis adynamic compiled language for the JavaVirtual Machine (JVM)
HELLO WORLD IN JAVA: publicclassMain { publicstaticvoidmain(String[]arguments){ System.out.println("HelloWorld!"); } } IN GROOVY: println"Hello,World!"
DATA TYPES Strings Functions Collections Lists Maps
STRINGS Single Quotes 'Hello,world!' Double Quotes --GString "Hello,$name" Multi-line Strings '''This is a multi-line string'''
STRING MANIPULATION Split defmyString='I<3Groovy' myString.tokenize('<3') -->[I,Groovy] Join defmyListOfStrings=['I','<3','Groovy'] myListOfStrings.join('') -->I<3Groovy
CLOSURES defa={params->println(params*2)} [1,2,3].eacha -->2 -->4 -->6 a(1) -->2
COLLECTIONS
Lists defmyList=['a','b',2] myList.multiply(2) -->['a','b','2','a','b','2']
SPECIAL FUNCTIONS Spread Dot myList*.multiply(2) -->['aa','bb',4]
MAPS defmyMap=[val1:'a',val2:'b',val3:'b'] myMap.values() -->['a','b',2] myMap.find{it.value=='b'} -->val2=b myMap.findAll{it.value=='b'} -->[val2:b,val3:b]
LOOPS
Each defmyList=[1,2,3] defresult=[] myList.each{ result<<it*2 } printlnresult -->[2,4,6]
Collect defmyList=[1,2,3] defresult=myList.collect{item-> item.multiply(2) } printlnresult -->[2,4,6]
Ranges (1..3).each{ printlnit*2 } -->2 -->4 -->6
FILE PROCESING
CREATING & WRITING TO FILES defmyFile=newFile('foo.txt') myFile.write'hello,world!!n' myFile.append('andhellouniverse!')
READING FILES defmyFile=newFile('foo.txt') myFile.eachLine{line-> defprocessedLine=line.replaceAll('hello','hi') printlnprocessedLine } -->hi,world! -->andhiuniverse!
THINGS TO REMEMBER Typingvariables is optional Some syntax is optional semi-colons parenthesis around function parameters explicitreturn statements The lastoperation completed is the defaultreturn value There is more than one wayto do almosteverything!
EXERCISES (HANDOUT) RESOURCES http://beta.groovy-lang.org/docs/groovy- 2.3.1/html/documentation/#_introduction http://beta.groovy-lang.org/docs/latest/html/groovy-jdk/

Groovy as a scripting language