论坛首页 编程语言技术论坛

Groovy语法糖一览

浏览 1751 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2015-11-16  

groovy都已经2.4.*版本了,好多新特性,对于其他语言不算新了,积累的语法糖其实都是1.8以后都有的

 

// 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
 
// *** 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的都还没有,这个才是这个语言最核心的设计了,大家多看些例子

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics