In the previous post, we created the GuessingGame as a functional object that was immutable. It was a little heavy as every operation resulted in a new object. Let’s refactor it a but and see where we land.
All that’s involved is passing in data that has the message, attempts and gameOver information. Let’s create a Tuple to hold this information. We’ll rewrite the play method to return a Tuple that holds this information. The play method will accept the guess number, target and attempts as input, compute the logic and return the tuple as output.
object GuessingGame { def play(guess:Int,params:(Int,Int)):(Int,String,Boolean) = { val message:String = if(guess>params._1) "Aim Lower" else if(guess < params._1) "Aim Higher" else "You've got it!!!" val gameOver:Boolean = if(guess == params._1) true else false (params._2+1,message,gameOver) } def main(args: Array[String]): Unit = { println("Enter a number between 1 and 100") var guess:Int = -1 val target:Int = (Math.random*100).asInstanceOf[Int] var game = (0,"",false) while(!game._3){ guess = readLine().toInt game = play(guess,(target,game._1)) println(game._2) } println("Attempts: " + game._1) } }
In the next post, let’s refactor this code further to make it further simple