Groovy学习摘要
发布时间:2020-12-14 16:49:14 所属栏目:大数据 来源:网络整理
导读:首先感谢翻译《Groovy in Action》Part 1的吴翊,其次感谢Groovy之父James Strachan 本文基于Groovy 1.8。 ======== 分割线 开始于2014-12-1 ======== 1,Groovy开始运行 Groovy定义和特性: 是一个基于Java虚拟机的敏捷动态语言。 构建在强大的Java语言之上
首先感谢翻译《Groovy in Action》Part 1的吴翊,其次感谢Groovy之父James Strachan 本文基于Groovy 1.8。 ======== 分割线 开始于2014-12-1 ======== 1,Groovy开始运行Groovy定义和特性: 是一个基于Java虚拟机的敏捷动态语言。举例,通过groovy控制台,输入如下代码来输出当前目录下所有的文件名(递归): groovy -e "new File('.').eachFileRecurse { println it }" // -e 直接执行和相同功能的java类相比,效率高低立见。 运行groovy的3种方式:
举例,执行groovy脚本: // Fibonacci.groovy current = 1 next = 1 10.times { //循环10次 print current + ' ' newCurrent = next next = next + current current = newCurrent } println '' groovy Fibonacci ===>1 1 2 3 5 8 13 21 34 55 2,语法基础#!/usr/bin/groovy /*BookTest.groovy 多行注释 不要命名成Book.groovy,报错: One of the classes is an explicit generated class using the class statement,the other is a class generated from the script body based on the file name. */ class Book{ ?? ?String title } def groovyBook = new Book() groovyBook.title = 'GIA' assert groovyBook.title == 'GIA'?// 单行注释 断言当前值equal(),非引用 // 引号中的串是GString类型,能作占位符 def nick = 'Gina' def book = 'Groovy in Action' assert "$nick is $book" == 'Gina is Groovy in Action' // =~表示匹配,/正则表达式/ assert 'a12345' =~ /d+/ // 所有的值都是对象 def x = 1 assert x + 2 == 3 assert x instanceof Integer // 简化集合操作 def roman = ['','I','II','III','IV','V','VI','VII'] roman[8] = 'VIII' assert roman.size() == 9 // 实是List,能自动扩容 assert roman instanceof List def y = 1..<10 // range形式,从1起,到10止,不包括10 assert y.contains(10) == false assert y.size() == 9 assert y.from == 1 assert y.to == 9 assert y.reverse() == 9..1 assert y instanceof List def http = [ ?? ?100 : 'CONTINUE',?? ?200 : 'OK',?? ?400 : 'BAD REQUEST' ?? ?] assert http[200] == 'OK' // 实是Map,冒号区分KV,通过下标Key找配对的Value assert http instanceof Map 3,闭包Closure泛用于函数式语言,类Lambda,使代码块被当成数据来引用执行,典型应用是回调函数,用{}包围,如果没有return,则闭包内的最后一行代码就是返回值。 /* ClosrueTest.groovy 闭包举例 */ [1,2,3].each{entry -> println entry} // 枚举打印 log = '' (1..10).each{ log += it } // 闭包参数隐式参数 assert log == '12345678910' map = ['a':1,'b':2] def doubleMethod (entry) { ? map[entry.key] = entry.value *2 } doubler = this.&doubleMethod // 应用方法作为闭包 map.each(doubler) assert map == ['a':2,'b':4] 4,结构控制if (null){ // 非null为真 assert false }else{ assert true } def clinks = 0 for (remainingGuests in 0..9) { // range迭代 clinks += remainingGuests } assert clinks == (10*9)/2 def age = 36 switch(age){??? // range case ?? ?case 16..20 : rate = 0.5 ; break ?? ?case 21..60 : rate = 0.7 ; break ?? ?default : rate = 0 } assert rate == 0.7 5,数据类型Groovy中所有数据都是对象。 5.1,数字
|