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?
Functional way to define an infinite loop is recursion:
@annotation.tailrec def process(availableRetries: Int): String = {
try {
return doSomething()
} catch {
case e: Exception => {
if (availableRetries < 0) {
throw e
}
}
}
return process(availableRetries - 1)
}
elbowich's retry
function without inner loop
function:
import scala.annotation.tailrec
import scala.util.control.Exception._
@tailrec def retry[A](times: Int)(body: => A): Either[Throwable, A] = {
allCatch.either(body) match {
case Left(_) if times > 1 => retry(times - 1)(body)
case x => x
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With