Match |
We will skip this material on match statements if we don't have time. Read it if you like, but it won't be covered on labs or exams.
The match statement can be more efficient and easier to read if there is a multi-way conditional statement whose branches depend on the integer values of an expression. For example, recall the following from above:
method onMousePress( point: Point) nextLineStarts := point def colorNumber: Number = randomIntFrom(1) to (3) if(colorNumber == 1) then lineColor := red elseif (colorNumber == 2) then lineColor := white else lineColor := blue
A match statement can choose the correct statements to execute based on the value of colorNumber (see program SpirographThreeColorMatch
def colorNumber: Number = randomIntFrom(1) to (3) match(colorNumber) case 1 -> lineColor := red case 2 -> lineColor := white case 3 -> lineColor := blue
Note that each branch is executed when the value of randomInt is an exact match for the number after case. It is possible to also write a default case to be executed if none of the others match. For example we could write
case {_ -> print "no match -- this wasn't supposed to happen!!"}
In the above case, the underscore is a wildcard that matches everything.
Note that you cannot use inequalities or other boolean expressions in cases.
Match |