Book Image

Mastering Gradle

Book Image

Mastering Gradle

Overview of this book

Table of Contents (17 chapters)
Mastering Gradle
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Control structures


In this section, we will discuss the basic control structures, namely the if…else statement, the switch statement, the for loop, and the while loop.

The if-else condition

The if…else condition in Groovy is similar to Java with one exception, how Groovy evaluates the logical if condition. In the following example, the if condition is evaluated true for both Boolean and int values. In Groovy, non-zero integers, non-null values, nonempty strings, initialized collections, and a valid matcher are evaluated as Boolean true values. This is known as Groovy Truths. Let's take a look at the following code:

def condition1 = true
int condition2 = 0
if(condition1){
  println("Condition 1 satisfied")
  if(condition2){
    println("Condition 2 satisfied")
  }else{
    println("Condition 2 failed")
  }
}else{
  println("Condition 1 failed")
}

Groovy also supports ternary operators (x? y: z), such as Java, which can be used to write the standard if-else logic:

(condition2> 0 )? println(...