内容简介:groovy变量类型都是对象类型的,基本类型都会被编译器转换成对象类型运行结果:
groovy变量类型都是对象类型的,基本类型都会被编译器转换成对象类型
int x = 10 println x.class double y = 3.14 println y.class
运行结果:
class java.lang.Integer class java.lang.Double
弱类型def定义方式,可以动态转换为其他类型
def x1 = 10 println x1.class def y1 = 3.14 println y1.class def z1 = "hello" println z1.class x1 = "shijiacheng" println x1.class
运行结果:
class java.lang.Integer class java.math.BigDecimal class java.lang.String class java.lang.String
什么时候使用强类型,什么时候弱类型
- 如果我们自己使用的时候,可以使用弱类型
- 如果我们定义的类要被其他类使用的话,建议使用强类型,这样就会固定参数的类型,防止类型转换的时候出错。
Groovy字符串详解
-
单引号定义字符串
def name = 'a single string' println name.class // 转义字符 def name2 = 'a single \'a\' string' println name2.class
运行结果:
class java.lang.String class java.lang.String
-
三引号定义字符串
def name3 = '''three sigle string''' println name3 println name3.class // 三引号可以自定带格式的字符串 def name4 = '''line1 line2 line3''' println name4
运行结果:
three sigle string class java.lang.String line1 line2 line3
-
双引号定义字符串
// 双引号定义普通字符串和单引号一样,都是java.lang.String类 def name5 = "hello world" println name5 println name5.class // 双引号还可以定义字符串表达式,这个时候返回的就不是java.lang.String类了 def name6 = "2 and 3 equals = ${2 + 3}" println name6 println name6.class
运行结果:
hello world class java.lang.String 2 and 3 equals = 5 class org.codehaus.groovy.runtime.GStringImpl
-
java.lang.String和GStringImpl相互转换是编译器帮我们做好的,我们可以任意转换这两种类型
String echo(String message){ return message } def result = echo(name6) println result println result.class
运行结果:
2 and 3 equals = 5 class java.lang.String
####
字符串方法
-
字符串填充
def str = "hello groovy" //中间填充 println str.center(15,'&') // 左边填充 println str.padLeft(15,'a')
运行结果:
&hello groovy&& aaahello groovy
-
字符串比较
// 字符串比较 def str2 = "hello" println str > str2
运行结果:
true
-
索引和字符串截取
// 字符串截取 println str[0] // 截取某一段字符串 println str[0..1]
运行结果:
h he
-
字符串减法
//字符串减法 println str - str2
运行结果:
groovy
-
其他方法
//字符串反转 println str.reverse() // 首字母大写 println str.capitalize() // 判断字符串是不是Int类型 println str.isNumber() // 字符串类型转换 println "123".toInteger()
运行结果:
yvoorg olleh Hello groovy false 123
逻辑控制
-
switch-case语句
def x = 1.23 def result = '' switch (x){ case 'foo': result = 'foo' break case [1.23,4,5,6,'inlist']://列表 result = 'list' break case 12..30://范围 result = 'range' break case Integer: result = 'integer' break case BigDecimal: result = 'big decimal' break default:result = 'default' } println(result)
-
循环语句
-
对范围的for循环
//对范围的for循环 def sum = 0 for(i in 0..9){ sum += i } println sum
-
对list的循环
// 对list的循环 sum = 0 for (i in [1,2,3,4,5,6,7,8,9]){ sum += i } println sum
-
对map的循环
// 对map的循环 sum = 0 for (i in ['lili':1,'lucy':2,'liming':3]){ sum += i.value } println sum
-
2.2 闭包
闭包:就是代码块
-
闭包的调用,闭包有两种调用方式
// 有参数的闭包 def clouser5 = {String name -> return "Hello ${name}!"} def result = clouser5('groovy') println result
运行结果
Hello groovy! Hello groovy!
-
有参数的闭包
// 有参数的闭包 def clouser2 = {String name -> println "Hello ${name}!"} clouser2.call('groovy') clouser2('groovy')
-
有多个参数的闭包
// 有多个参数的闭包 def clouser3 = {String name,int age -> println "Hello ${name},My age is ${age}"} clouser3.call('groovy',4) clouser3('groovy',4)
-
闭包的默认参数
// 闭包的默认参数 def clouser4 = { println "Hello ${it}!"} clouser4.call('groovy') clouser4('groovy')
-
闭包的返回值
// 闭包返回值 def clouser5 = {String name -> return "Hello ${name}!"} def result = clouser5('groovy') println result
-
闭包都有返回值
//闭包体没有写return的话其实也是有返回值的 def clouser6 = {String name -> println "Hello ${name}!"} def result2 = clouser6('groovy') println result2
运行结果:
Hello groovy! null
闭包的用法
-
upto方法
// 计算指定number的阶乘 int fab(int number){ int result = 1 1.upto(number,{num -> result *= num}) return result } int x = fab(5) println x
查看upto方法的源码
public static void upto(Number self, Number to, @ClosureParams(FirstParam.class) Closure closure) { int self1 = self.intValue(); int to1 = to.intValue(); if (self1 > to1) { throw new GroovyRuntimeException("The argument (" + to + ") to upto() cannot be less than the value (" + self + ") it's called on."); } else { for(int i = self1; i <= to1; ++i) { closure.call(i); } } }
-
downto方法
int fab2(int number){ int result = 1 number.downto(1){ num -> result*=num } result result } int y = fab2(5) println y
-
time方法
// 计算累加值 int cal(int number){ int result = 0 number.times { num -> result += num } return result } int z = cal(101) println z
闭包与字符串结合使用
-
each遍历
String str = 'the 2 and 3 is 5' //each遍历 str.each { String temp -> print temp.multiply(2) }
运行结果:
tthhee 22 aanndd 33 iiss 552
-
find找到符合条件的第一个
// find找到符合条件的第一个 println str.find{ String s -> s.isNumber() }
运行结果:
-
findAll找到所有符合条件的
// findall 找到所有符合条件 def list = str.findAll{ String s -> s.isNumber() } println list.toList()
运行结果:
[2, 3, 5]
-
any返回str中是否有任意一项符合条件
// any 返回str中是否有符合条件的任何一项 def result = str.any { String s -> s.isNumber() } println result
运行结果:
true
-
every 返回str中的每一项是否都符合条件
// every 返回str的每一项是否都符合条件 def result2 = str.every { String s -> s.isNumber() } println result2
运行结果:
false
-
将string转换为list
// 将string转为list def list2 = str.collect { it.toUpperCase() } println list2.toListString()
运行结果:
[T, H, E, , 2, , A, N, D, , 3, , I, S, , 5]
闭包进阶讲解
-
闭包中的三个重要变量
/** * 闭包的三个重要变量 this,owner,delegate */ def scriptCloser = { //代表闭包定义处的类 println "scriptCloser this:"+this // 代表闭包定义处的类或者对象 println "scriptCloser owner:"+owner // 代表任意对象,默认闭包定义处的类 println "scriptCloser delegate:"+delegate } scriptCloser.call()
运行结果:
scriptCloser this:variable.closerstudy@649bec2e scriptCloser owner:variable.closerstudy@649bec2e scriptCloser delegate:variable.closerstudy@649bec2e
-
定义了一个内部类
//定义了一个内部类 class Person{ def static classCloser = { println "classCloser this:"+this println "classCloser owner:"+owner println "classCloser delegate:"+delegate } def static say(){ def classCloser = { println "methodClassCloser this:"+this println "methodClassCloser owner:"+owner println "methodClassCloser delegate:"+delegate } classCloser.call() } } Person.classCloser.call() Person.say()
运行结果:
classCloser this:class variable.Person classCloser owner:class variable.Person classCloser delegate:class variable.Person methodClassCloser this:class variable.Person methodClassCloser owner:class variable.Person methodClassCloser delegate:class variable.Person
-
去掉内部类中的静态方法
//定义了一个内部类 class Person{ def classCloser = { println "classCloser this:"+this println "classCloser owner:"+owner println "classCloser delegate:"+delegate } def say(){ def classCloser = { println "methodClassCloser this:"+this println "methodClassCloser owner:"+owner println "methodClassCloser delegate:"+delegate } classCloser.call() } } Person p = new Person() p.classCloser.call() p.say()
运行结果:
classCloser this:variable.Person@932bc4a classCloser owner:variable.Person@932bc4a classCloser delegate:variable.Person@932bc4a methodClassCloser this:variable.Person@932bc4a methodClassCloser owner:variable.Person@932bc4a methodClassCloser delegate:variable.Person@932bc4a
-
闭包中定义一个闭包
// 闭包中定义一个闭包 def nestCloser = { def innerCloser = { println "innerClassCloser this:"+this println "innerClassCloser owner:"+owner println "innerClassCloser delegate:"+delegate } innerCloser.call() } nestCloser.call()
运行结果:
innerClassCloser this:variable.closerstudy@1cbb87f3 innerClassCloser owner:variable.closerstudy$_run_closure2@3e84448c innerClassCloser delegate:variable.closerstudy$_run_closure2@3e84448c
-
修改默认的delegate
// 闭包中定义一个闭包 def nestCloser = { def innerCloser = { println "innerClassCloser this:"+this println "innerClassCloser owner:"+owner println "innerClassCloser delegate:"+delegate } innerCloser.delegate = p//修改默认的delegate innerCloser.call() } nestCloser.call()
运行结果:
innerClassCloser this:variable.closerstudy@22e357dc innerClassCloser owner:variable.closerstudy$_run_closure2@63a12c68 innerClassCloser delegate:variable.Person@446293d
-
闭包的委托策略
// 闭包的委托策略 class Student{ String name def pretty = { "My name is ${name}" } String toString(){ pretty.call() } } class Teacher{ String name } def stu = new Student(name: Sarash ) def tea = new Teacher(name: Shijiacheng ) println stu.toString() stu.pretty.delegate = tea stu.pretty.resolveStrategy = Closure.DELEGATE_ONLY println stu.toString()
运行结果:
My name is Sarash My name is Shijiacheng
##
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Cracking the Coding Interview
Gayle Laakmann McDowell / CareerCup / 2015-7-1 / USD 39.95
Cracking the Coding Interview, 6th Edition is here to help you through this process, teaching you what you need to know and enabling you to perform at your very best. I've coached and interviewed hund......一起来看看 《Cracking the Coding Interview》 这本书的介绍吧!