In the earlier post on Scala, we created the Guessing Game class using imperative style. Now you’ve the GuessingGame class implemented using functional style. This is the first attempt in doing that.
Couple of points to keep in mind here is in the functional style the classes are designed to be immutable and the variables are designed to be final using the val keyword. Here’s the code snippet that has the GuessingGame class configured as a functional class.
class GuessingGame(theTarget:Int,theAttempts:Int,theMessage:String,theGameOver:Boolean) { val target:Int = theTarget; val attempts:Int = theAttempts; val message:String = theMessage; val gameOver:Boolean = theGameOver; def play(guess:Int):GuessingGame = { new GuessingGame( target, attempts+1, if(guess>target) "Aim Lower" else if(guess < target) "Aim Higher" else "You've got it!!!", if(guess == target) true else false ) } } object GuessingGameUser { def main(args:Array[String]){ var game:GuessingGame = new GuessingGame((Math.random*100).asInstanceOf[Int],0,"",false) println("Enter a number between 1 and 100") var guess:Int = -1 while(!game.gameOver){ guess = readLine().toInt game = game.play(guess) println(game.message) } println("Attempts: " + game.attempts) } }
Though it’s functional there’s a bit of weight added to the code. In the next post let’s see how we can refactor it and make it lightweight.