Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
def x= 7
if( x > 4 ){ println 'x is greater than 4' } //if-statement (no 'else' clause)

if( x > 4 ) println 'x is greater than 4'
                                    //curlies optional if only one statement
//if-else statement...
if( x > 4 ){
  println 'x is greater than 4'
}else{
  println 'x is less than or equal to 4'
}

if( x > 8 ) println 'x is greater than 8'
                              //again, curlies optional if only one statement
else println 'x is less than or equal to 8'

//an 'else' clause always belongs to

def result
if( x > 4 )
  if( x > 8 ) result= 'x is greater than 8'
  else result= 'x is less than or equal to 8'
          //a single 'else' with two 'if' clauses belongs to the innermost
assert result == 'x is less than or equal to 8'

...

Code Block
def values= [
    'abc': 'abc',
    'xyz': 'list',
       18: 'range',
       31: BigInteger,
  'dream': 'something beginning with dr',
     1.23: 'none',
]
values.each{
  def result
  switch( it.key ){
    case 'abc': //if switched expression matches case-expression, execute all
                //statements until 'break'
      result= 'abc'
      break
    case [4, 5, 6, 'xyz']:
      result= 'list'
      break
    case 'xyz': //this case is never chosen because 'xyz' is matched by
                //previous case, then 'break' executed
      result= 'xyz'
      break
    case 12..30:
      result= 'range'
      break
    case Integer:
      result= Integer //because this case doesn't have a 'break', result
                      //overwritten by BigInteger in next line
    case BigInteger:
      result= BigInteger
      break
    case ~/dr.*/:
      result= 'something beginning with dr'
      break
    case {it instanceof Integer && it>30}: //use Closure
      result= 'result is > 30'
      break
    default:
      result= 'none'
  }
  assert result == it.value
}

...

The precedence heirarchy of the operators, some of which we haven't looked at yet, is, from highest to lowest:

Code Block
  $(scope escape)
  new ()(parentheses)
  [](subscripting) ()(method call) {}(closable block) [](list/map)
  . ?. *. (dots)
  ~ ! $ ()(cast type)
  **(power)
  ++(pre/post) --(pre/post) +(unary) -(unary)
  * / %
  +(binary) -(binary)
  << >> >>> .. ..<
  < <= > >= instanceof in as
  == != <=>
  &
  ^
  |
  &&
  ||
  ?:
  = **= *= /= %= += -= <<= >>= >>>= &= ^= |=

...