I am picking up Scala recently. I have been used to C and Java before. I am wondering if there is a more elegant way of asking for input repeatedly until correct input is given.
val choiceType = {
var in = ""
var pass = false
do {
in = readLine()
pass = in match {
case "1" => println("Not implemented"); true
case "2" => println("Not implemented"); true
case "3" => println("Not implemented"); true
case "4" => println("Not implemented"); true
case "5" => println("Thanks for using."); true
case _ => println("Error input. Please enter again. (Possible value: 1 - 5)"); false
}
} while (!pass)
in.toInt
}
if (choiceType == 5) System.exit(0)
I am wondering if there is a better way of doing this in Scala?
You could use either
Iterate.continuallyto do the same thing over and over again until you impose some stopping condition (withdropWhile), or you could useIterator.iterateto give you the previous line in case you want to use it in your error message:The way this works is by starting with a readLine, and then if it needs another line it announces an error message based on the previous line (obviously that one was wrong) and reads another line. You then use a
collectblock to pick out your correct input; the wrong input just falls through without being collected. In this case, since you want to turn it into an integer, I’m just passing the line through. Now, we only want one good entry, so we get thenextone and convert it to an int.You could also use a recursive function to do a similar thing:
Here the trick is that in the case where you get wrong input, you just call the function again. Since that’s the last thing that happens in the function, Scala will avoid a true function call and just jump to the beginning again (tail-recursion), so you won’t overflow the stack.