// no class declareation -> subclass of Scriptpackage com.innohub.syntax// 输出太多,这个作为一块开始的标示String hr = (1..10).collect{'***'}.join(' ')def pp = {String str, obj -> println str.padRight(40, ' ') + obj}pp 'My Class', this.class.namepp 'I am a Script object', this in Script// *** 多变量赋值def (aa, bb) = [1, 2]pp 'aa is ', aapp 'bb is ', bb// swap(aa, bb) = [bb, aa]pp 'aa is ', aapp 'bb is ', bb// *** currydef cl1 = {int a, b, c -> a + b + c}def cl1Curry1 = cl1.curry(1)pp 'curry sum', cl1Curry1(2, 3)// closure call itselfdef sumRecurse = {int n -> n == 1 ? 1 : n + call(n - 1)}pp 'sum 10', sumRecurse(10)// 参考:Groovy基础——Closure(闭包)详解 http://attis-wong-163-com.iteye.com/blog/1239819// *** Object withclass Test { def fun1() { println 'a' } def fun2() { println 'b' } def fun3() { println 'c' } } def test = new Test() test.with { fun1() fun2() fun3() } // *** string/gstringprintln hr// 调用命令行def process = "cmd /c dir".execute()pp 'dir output', process.textpp '1+1 = ?', '${1+1}'pp '1+1 = ?', "${1+1}"// 这里写sql之类的完爆StringBuffer吧,groovy编译后用StringBuilder优化pp '1+1 = ?', ''' ${1+1}'''pp '1+1 = ?', """ ${1+1}"""// *** patternprintln hr// 难道所有的语言不都应该这么写正则自变量么?def pat = /^(\d+)$/pp 'I am', pat.class.namedef patCompiled = ~/\d/pp 'And you are', patCompiled.class.namepp 'is 1234 match ? ', '1234' ==~ pat// 需要中间变量def mat = '1234' =~ patpp 'how 1234 match', mat[0][1]// *** list/map/setprintln hr// 运算符重载def ll = []pp 'I am', ll.class.namell << 1ll << 2ll << 3pp 'My length is', ll.size()def set = [] as HashSetpp 'I am', set.class.nameset << 1set << 2set << 2pp 'My length is', set.size()def map = [:] // as HashMap or HashMap map = [:]map.key1 = 'val1'pp 'R u a LinkedHashMap?', map instanceof LinkedHashMap// 一堆语法糖// 不完整的切片pp 'Some of me', ll[1..-2]pp 'I have 2', 2 in set// 和instanceof一样class Parent implements Comparable{ int money // 重载 def Parent plus(Parent another){ new Parent(money: this.money + another.money) } def int compareTo(obj){ if(obj in Parent) this.money - obj.money 0 }}class Child extends Parent { }def p1 = new Parent(money: 100)def p2 = new Parent(money: 200)pp 'My parent is richer', p1 < p2def p3 = p1 + p2pp 'Let us marry, our money will be', p3.moneydef child = new Child()pp 'My son', child in Childpp 'My son like me', child in Parent// each every any collect grep findAll find eg.def listOfStudent = [[name: 'kerry'], [name: 'tom']]pp 'your names?', listOfStudent*.name.join(',')def calSum = {int i, int j, int k -> i + j + k}pp 'let us do math', calSum(*ll)// 哎,费脑筋啊def listFromRange = [*(1..20)]pp 'another', listFromRange.size()// *** ioprintln hr// 又一堆语法糖// eg. new File('苍井空.av').newOutputStream() << new Url(url).bytesdef f = new File('MakeYouPleasure.groovy.output')f.text = 'xxx'f.newOutputStream() << 'yyy'pp 'file content', f.text.size()f.withPrintWriter{w -> w.println 'zzz'}pp 'file line number', f.readLines().size()// *** ==println hrpp 'oh aa == aa of cause', 'aa' == "aa"String num = 'aa'pp 'again?', 'aa' == "${num}"pp 'number is number, string is string', 0 == '0'// 这里需要(),或要有中间变量pp 'list match!', [1, 1] == [1, 1]pp 'map match!', ['a':'1'] == ['a':'1']// 这里用is进行引用比较pp 'two lists', [1, 1].is([1, 1])// *** ifprintln hrpp "'' is", !''pp "'1' is", !'1'pp "[] is", ![]pp "[1] is", ![1]pp "[:] is", ![:]pp "[1:1] is", ![1:1]pp "0 is", !0pp "1 is", !1// *** null ifprintln hrdef one = nullpp 'null name is null', one?.nameone = [name: 'kerry']pp 'my name is', one?.name// *** as/closureprintln hrpp '1 is a integer, yes', '1' as int// refer asTypedef list4as = [2, 3]def strs = list4as as String[] // or String[] strs = list4aspp 'list can be array', strsclass User { int age boolean isOld(){ age > 50 }}interface Operator { def doSth()}// get/set方法省略不用写,造数据也简单def user = [age: 51] as Userpp 'map can be object, is it old?', user.isOld()// 接口也一样,但是都是不要类型和参数def myOperator = [doSth: { 10}] as Operatorpp 'closure can be a method, do sth!', myOperator.doSth()// Closure是一个类实例,当时一等公民def doSth = myOperator.&doSthpp 'do again', doSth()// 所以可以付给其他对象,这里很像js里的prototype吧Parent.metaClass.hello = doSthpp 'do again, but why u?', child.hello()Parent.metaClass.hi = {String name, int age -> // 变老了 name + ((age ?: 0) + delegate.hello())}pp 'how old?', child.hi('son', 5)// *** assertprintln hrassert 1 == 1// *** ant builderprintln hrdef ant = new AntBuilder()// 这就是语法变种,省略了括号,闭包一般都是最后一个参数// 看gradle的文件时候,别以为那是配置文件,那个也是groovy。。。ant.echo message: 'hi'ant.copy todir: '/', { fileset dir: './', { include name: 'Make*.groovy' }}// 当然ant所有的功能这里都有,refer gygy.groovy// SwingBuider/MarkupBuilder略// *** xmlprintln hrdef parser = new XmlParser()def root = parser.parseText('''''')root.student.each{ pp 'student name', it.@name}// 还有grape,不过现在都是gradle了// 还有Sql组件// 其实上面都是语法糖,面向metaClass的都还没有,这个才是这个语言最核心的设计了,大家多看些例子