Scala while(true) type mismatch? Infinite loop in scala?
infinite-loop, loops, scala
Solution
Based on senia, elbowich and dave's solutions I used following:
@annotation.tailrec
def retry[T](availableRetries: Int)(action: => T): T = {
try {
return action
} catch {
case e: Exception if (availableRetries > 0) => { }
}
retry(availableRetries - 1)(action)
}
Which can be then used as elbowich and dave's solutions:
retry(3) {
// some code
}
Problem
Why following code ``` def doSomething() = "Something" var availableRetries: Int = 10 def process(): String = { while (true) { availableRetries -= 1 try { return doSomething() } catch { case e: Exception => { if (availableRetries < 0) { throw e } } } } } ``` produces following compiler error ``` error: type mismatch; found : Unit required: String while (true) { ^ ``` ? This works ok in C#. The while loops forever, so it cannot terminate, therefore it cannot result something else than string. Or how to make infinite loop in Scala?