Groovy语法糖一览

// no class declareation -> subclass of Script
package com.innohub.syntax

// 输出太多,这个作为一块开始的标示
String hr = (1..10).collect{'***'}.join(' ')
def pp = {String str, obj ->
	println str.padRight(40, ' ') + obj
}

pp 'My Class', this.class.name
pp 'I am a Script object', this in Script

// *** 多变量赋值
def (aa, bb) = [1, 2]
pp 'aa is ', aa
pp 'bb is ', bb

// swap
(aa, bb) = [bb, aa]
pp 'aa is ', aa
pp 'bb is ', bb

// *** curry
def cl1 = {int a, b, c ->
	a + b + c
}
def cl1Curry1 = cl1.curry(1)
pp 'curry sum', cl1Curry1(2, 3)

// closure call itself
def 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 with
class Test {  
    def fun1() { println 'a' }  
    def fun2() { println 'b' }  
    def fun3() { println 'c' }  
}  
def test = new Test()  
test.with {  
    fun1()  
    fun2()  
    fun3()  
}  

// *** string/gstring
println hr

// 调用命令行
def process = "cmd /c dir".execute()
pp 'dir output', process.text

pp '1+1 = ?', '${1+1}'
pp '1+1 = ?', "${1+1}"
// 这里写sql之类的完爆StringBuffer吧,groovy编译后用StringBuilder优化
pp '1+1 = ?', '''
	${1+1}
'''
pp '1+1 = ?', """
	${1+1}
"""

// *** pattern
println hr

// 难道所有的语言不都应该这么写正则自变量么?
def pat = /^(\d+)$/
pp 'I am', pat.class.name
def patCompiled = ~/\d/
pp 'And you are', patCompiled.class.name

pp 'is 1234 match ? ', '1234' ==~ pat
// 需要中间变量
def mat = '1234' =~ pat
pp 'how 1234 match', mat[0][1]

// *** list/map/set
println hr

// 运算符重载
def ll = []
pp 'I am', ll.class.name
ll << 1
ll << 2
ll << 3
pp 'My length is', ll.size()

def set = [] as HashSet
pp 'I am', set.class.name
set << 1
set << 2
set << 2
pp '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 < p2
def p3 = p1 + p2
pp 'Let us marry, our money will be', p3.money

def child = new Child()
pp 'My son', child in Child
pp '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()

// *** io
println hr

// 又一堆语法糖
// eg. new File('苍井空.av').newOutputStream() << new Url(url).bytes
def 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 hr

pp '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])

// *** if
println hr

pp "'' is", !''
pp "'1' is", !'1'
pp "[] is", ![]
pp "[1] is", ![1]
pp "[:] is", ![:]
pp "[1:1] is", ![1:1]
pp "0 is", !0
pp "1 is", !1

// *** null if
println hr

def one = null
pp 'null name is null', one?.name
one = [name: 'kerry']
pp 'my name is', one?.name

// *** as/closure
println hr

pp '1 is a integer, yes', '1' as int

// refer asType

def list4as = [2, 3]
def strs = list4as as String[] // or String[] strs = list4as
pp 'list can be array', strs

class User {
    int age

	boolean isOld(){
		age > 50
	}
}

interface Operator {
	def doSth()
}

// get/set方法省略不用写,造数据也简单
def user = [age: 51] as User
pp 'map can be object, is it old?', user.isOld()

// 接口也一样,但是都是不要类型和参数
def myOperator = [doSth: {
	10
}] as Operator
pp 'closure can be a method, do sth!', myOperator.doSth()

// Closure是一个类实例,当时一等公民
def doSth = myOperator.&doSth
pp 'do again', doSth()

// 所以可以付给其他对象,这里很像js里的prototype吧
Parent.metaClass.hello = doSth
pp '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)

// *** assert
println hr

assert 1 == 1

// *** ant builder
println hr

def ant = new AntBuilder()
// 这就是语法变种,省略了括号,闭包一般都是最后一个参数
// 看gradle的文件时候,别以为那是配置文件,那个也是groovy。。。
ant.echo message: 'hi'
ant.copy todir: '/', {
	fileset dir: './', {
		include name: 'Make*.groovy'
	}
}
// 当然ant所有的功能这里都有,refer gygy.groovy

// SwingBuider/MarkupBuilder略

// *** xml
println hr

def parser = new XmlParser()
def root = parser.parseText('''
<dept name="one">
	<student name="1" />
	<student name="2" />
</dept>
'''
)
root.student.each{
	pp 'student name', it.@name
}


// 还有grape,不过现在都是gradle了
// 还有Sql组件

// 其实上面都是语法糖,面向metaClass的都还没有,这个才是这个语言最核心的设计了,大家多看些例子


转载于:https://my.oschina.net/u/2000379/blog/529195

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值