Continuing with the posts on Scala where we implemented Guessing game in imperative style and a in a couple of ways using the functional style, let’s implement it using pattern matching facility.
Pattern matching provided in Scala is one of the most widely used features. It’s a glorified form of switch-case statements, though comparing it with a switch-case construct would mean belittling it. Given below is the guessing game implemented using pattern matching feature in Scala.
object GuessingGamePattern { val target:Int = (Math.random*100).asInstanceOf[Int] def play(guess:Int):Boolean = { guess match { case num:Int if (num > target) => println("Aim Lower");false case num:Int if (num < target) => println("Aim Higher");false case num:Int if (num == target)=> println("You've got it!!!");true } } def main(args:Array[String]):Unit = { println("Enter a number between 1 and 100") var gameOver = false var guess:Int = -1 var attempts:Int = 0 while(!gameOver){ guess = readLine().toInt gameOver = play(guess) attempts += 1 } println("Attempts: " + attempts) } }
If you take a close look at the play method, you’d notice we’ve used pattern matching. You pass the guess value to the play method and try to match it with the condition and return a boolean value.
Now that, we’ve been playing with guessing game in different ways, we’ll take up another example and implement it using Scala