if, else and the ternary

A condition in Groovy is any value, tested with the rule of the truthiness lesson. The if statement has the shape of Java: a block, then else if, then else.

A chain of branches

grade.groovy

def score = 82 if (score >= 90) { println 'A' } else if (score >= 80) { println 'B' } else if (score >= 70) { println 'C' } else { println 'F' }

groovy grade.groovy

B

The braces are required around a block; a one-line branch may drop them, and the course keeps them because a second statement added to a branch without braces is a classic bug. CodeNarc's braces ruleset asks for the same.

The ternary and Elvis

label.groovy

def user = [name: 'Ada', nickname: null, active: true] def label = user.nickname ?: user.name println label println(user.active ? 'active' : 'inactive') def greeting = user.active ? "Hello, ${label}" : 'Goodbye' println greeting

groovy label.groovy

Ada
active
Hello, Ada

condition ? a : b is an expression, so it can stand on the right of an assignment. ?: keeps the left side when it is true and evaluates it once, which is the shortest way to write a default.

The value of a branch

A method returns the value of its last expression, so the branches of an if at the end of a method are its return values. No return keyword is needed, and CodeNarc calls one redundant:

grade_method.groovy

String grade(int score) { if (score >= 90) { 'A' } else if (score >= 80) { 'B' } else { 'C' } } println grade(95) println grade(85) println grade(60)

groovy grade_method.groovy

A
B
C

An if used as a statement has no value: this is the method return at work, not an if expression like the one Ruby has.

Related

Автор статьи: Arthur Isaev