...
| Code Block |
|---|
class A{
int x,y
A(x,y){ this.x=x; this.y=y }
String toString(){ "x: $x; y: $y" }
}
def a= [1,2] as A
assert a.class == A && a.toString() == 'x: 1; y: 2'
|
Conditional Statements
The if and if-else statements let us choose subsequent statements to execute based on a condition:
...
| Code Block |
|---|
class A{
boolean isCase(Object switchValue){ //'isCase' method used for case-expression
if(switchValue == 'Hi') return true
else return false
}
}
switch( 'Hi' ){
case new A():
assert true
break
default:
assert false
}
class B{
boolean equals(Object switchValue){ //'equals' method used for case-expression
this.class == switchValue.getClass()
}
}
switch( new B() ){
case new B():
assert true
break
default:
assert false
}
|
Iterative Statements
The while statement lets us iterate through a block of code:
...
| Code Block |
|---|
yonder: def d= 4
there: {
def e= 5
here: if( e == 5 ){
def f= 6
there: def g= 7 //label can repeat a previously-used outer label
}
}
there: def h= 8
//label can repeat a previously-used label at same syntactic level
def i=0, j=0
outer: while( i<5 ){ //labelling a while loop is especially useful...
j= 0
i++
while( j<5 ){
j++
if( i==3 && j==2 ) break outer
//...because we can break out of a specified labelled while loop
}
}
assert i==3 && j==2
def outer= 0, inner= 0
outer: while( outer != 5 && outer != 8 ){
//label can have same name as any variables
inner= 0
outer++
while( inner<5 ){
inner++
if( outer==5 ){
outer++
continue outer
//we can also continue on from a specified labelled while loop
}
}
}
assert outer==8
|
For-Statements
For-statements are complex yet powerful iterative statements with many possible formats. When 'in' is used in the iterative context of a for-statement, the 'iterator' method of the target is invoked. The 'iterator' method must return an Iterator, defining at least the 'hasNext' and 'next' methods:
...
| Code Block |
|---|
//two initializers and two incrementers...
def list= []
for(def i=0; def j=10; i<5; i++; j++){ //the middle expression is the condition
list<< i + j
}
assert list == [10, 12, 14, 16, 18]
//three initializers and three incrementers...
list= []
for(def i=0; def j=10; def k=20; i<3; i++; j++; k++){
list<< i + j + k
}
assert list == [30, 33, 36]
//when there's an even number of expressions, the condition is just before
//the middle...
list= []
try{
def i=0
for(def j=10; i<5; i++; j++){
list<< i + j
}
}
assert list == [10, 12, 14, 16, 18]
//we can force in more initializers than incrementers by using
//'null' statements...
list= []
for(def i=0; def j=10; i<5; i++; null ){
list<< i + j
}
assert list == [10, 11, 12, 13, 14]
|
Operator Overloading
The precedence heirarchy of the operators, some of which we haven't looked at yet, is, from highest to lowest:
...