There are millions of examples out there on all this, but here is a little program that shows the case pattern guards and function literals
class NumGuessCase(guess: Int) {
def guessNum(read: () => Int, disp: String => Unit): Unit = _guessNum(read, disp)
private def _guessNum(read: () => Int, disp: String => Unit, times: Int = 0): Unit = {
disp("Please enter guess :> ")
read() match {
case `guess` => disp("You guessed right in " + (times+1));
case a if a > guess => disp ("You guessed too high");
_guessNum(read, disp, times+1)
case a if a < guess => disp ("You guessed too low");
_guessNum(read, disp, times+1)
}
}
}
The guessNum method takes two arguments, read, and disp. Parameter “read” is a function which when invoked should return the user’s guess. “disp” (display) represents a function which is responsible for the output of the messages by the guessNum function. So the client of the guessNum can pass in as arguments a function that accepts user input and another one that displays the messages back to user and in our case we just use system console for this interaction (see the NumGuesCase companion object shown below).
The part I was testing out was the case pattern guards, the second case statement would match only if the pattern guard (“a > guess”) returns true. We could have used a default catch all pattern (“_”) as the last case statement. The first statement uses a variable pattern and is why you have to use the ` (backquote) symbol.
object NumGuesCase extends Application {
new NumGuessCase(new java.util.Random().nextInt(100)).guessNum(readInt,println)
}
This is how you would use the guessNum method, just pass in a readInt and println method. Scala compiler would capture these methods as Fuction objects and pass it to our guessNum method and since they both Type check with the Function signature it works.
If anyone is trying this out , please be aware of the missing main method bug (pre 2.8.0) as detailed out here