Continuing with the functional style of coding in Scala, let’s implement the guessing game using Lazy Stream collections in Scala. Streams in Scala are lazily evaluated collections. The Stream collection is appended with the values as you go on and on. So it’s an infinite collection.
Here’s the code to implement the Guessing game using Stream.
val target = (Math.random * 100).toInt def playGame(ignoreParam: Boolean = true) = { print("Please enter your guess:") val guess = Console.readInt val compared = guess.compare(target) val (message, playAgain) = compared match { case -1 => ("Aim higher", true) case 0 => (s"You got it ", false) case 1 => ("Aim lower", true) } if(playAgain) println(message) playAgain } val play : Stream[Boolean] = Stream.iterate(true)(playGame) val attempts = play.takeWhile { playAgain => playAgain }.toList.size println(s"You got it in $attempts attempts")