Return from loop

Hi,

I am implementing a simple program: A user is asked for his age until the answer is right.

def defaultval: String = ""

def validator(answer: String): Boolean = (answer matches """\d+""") && answer.toInt > 0
  
def modifier(answer: String): Int = answer.toInt
   
def ask(question: String): String = if (defaultval equals "") "10" else defaultval
  
def validate(question: String, error: String="Error. Invalid answer.") = 
  while (!validator(ask)) print("error")

println(ask("What is your age? "))

Note that I tried my code on scalafiddle, therefore it has no object Main and readLine in ask. My question basically is: Is there a beautiful one-liner for validate? Something like "While the answer is not valid, print an error and finally return the correct (modified) answer …

Any ideas? I am pretty sure that Scala has a beautiful solution to that. It always has beautiful solutions ;-)

Hey @simon-gunacker,

https://users.scala-lang.org/ is a better place to ask general Scala questions. This forum is more focused on Akka, Play, Lagom and sbt.

Best.

Thank you. I will port my question there.