Groovy In Action 学习笔记(六) Groovy语法基础(四)

xiaoxiao2024-04-22  36

1.   闭包 closures

a)    可执行代码段

 

def range = 1..3 // 定义一个 Range

range.each() { num -> // num 是闭包的参数

    println num // 使用参数

}

 

// 输出结果,表示闭包的这个代码段被执行了 3 次。

1

2

3

 

b)    it 的用法

 

def range = 1..3

range.each(){// 只有一个参数,则可以省略

    println it // 一个参数,使用 it

    println it.class

}

 

2.   流程控制语法 Control structures

a)     if else, while, switch, and try-catch-finally

 

b)    if null 。可以将 null false 等同,非 null true 等同。

 

if (false) { // 传统 java if 只能判断 true false

assert false // 该语句会抛出 AssertionError 异常

} else {

assert true

}

 

if (null) { // Groovy if 还可以判断 null 和非 null

assert false

} else {

assert true

}

 

c)    switch case 的语法。

        i.       Java 只对 int,byte,char 支持

       ii.       Groovy 提供对 String 的支持

 

def x = 'AB'

switch(x) {

case 'AB': println 'AB'; break;

case 'CD': println 'CD'; break;

default: println 'Default'

}

 

// 输出结果:

AB

 

d)     in 的语法。可用于 Range List

 

def list = 0..4

for (j in list) {

    assert j == list[j]

}

 

转载请注明原文地址: https://www.6miu.com/read-5015163.html

最新回复(0)