Groovy User Guide (7)

xiaoxiao2021-03-06  42

7, logical branch

(1) IF-ELSE statement

l Groovy provides the same IF-ELSE statement in Java

x = false

Y = false

IF (! x) {

x = true

}

askX == True

IF (x) {

x = false

} else {

Y = true

}

askERT X == Y

l Groovy also supports three yuan operators

Y = 5

X = (Y> 1)? "worked": "failed"

askERT X == "worked"

(2) SWITCH statement

l Groovy's Switch statement is compatible with Java code, and the difference between Groovy's Switch statement can handle various types of Switch values. You can do various types of matching.

Ø Case value Match the Switch value for the class name as class instance

Ø Case value is a string of the regular expression matching the Switch value matching the regular expression

Ø Case value is a collection of Switch values ​​included in the collection, including Ranges

Ø In addition to the above, the Case value matches the Switch value.

X = 1.23

Result = ""

Switch (x) {

Case "foo":

Result = "Found foo"

// Lets Fall Through

Case "bar":

Result = "bar"

Case [4, 5, 6, 'inList']:

Result = "List"

Break

Case 12..30:

Result = "Range"

Break

Case Integer:

Result = "integer"

Break

Case Number:

Result = "Number"

Break

DEFAULT:

Result = "default"

}

askERT RESULT == "Number"

l Switch statement works: Switch statement calls iscase (SwitchValue) method when doing matching case value, is default call (switchValue), but has been overloaded into various types, such as classes, regular expressions, collections, etc.

l You can create custom match classes, add iSCase (SwitchValue) to provide custom match types.

转载请注明原文地址:https://www.9cbs.com/read-112657.html

New Post(0)