首页 > 代码库 > Groovy学习笔记-使用多赋值

Groovy学习笔记-使用多赋值

1.方法返回多个结果:返回数组,将多个变量逗号隔开,放在左侧圆括号中

def splitName (fullName) {     fullName.split(‘ ‘)}def (firstName, lastName) = splitName(‘Tom Smith‘)println "$lastName, $firstName"/* output Smith Tom*/

2.交换变量:将欲交换的变量放在左侧圆括号内,右侧中括号相反顺序放置

def name1 = ‘aaa‘def name2 = ‘bbb‘(name1, name2) = [name2, name1]println "$name1, name2"/*outputbbb, name2*/

3.使用多赋值:如果有多余的变量,则会设置变量为null

def (String cat, String mouse) = [‘Tom‘, ‘Jerry‘, ‘Spike‘]println "$cat, $mouse"def (first, second, third) = [‘Tom‘, ‘Jerry‘]println "$first, $second, $third"/*outputTom, JerryTom, Jerry, null*/

 

Groovy学习笔记-使用多赋值