Suppose I've got a function foo:Int => Try[Int] and I need to call it with retries. That is, I need to call it till it returns Success at most k times.
I am writing a function retry like that:
def retry(k: retries)(fun: Int => Try[Int]): Try[Int] = ???
I want retry to return either Success or the last Failure. How would you write it ?
This is the one I use, which is generic over any thunk returning T:
@tailrec
final def withRetry[T](retries: Int)(fn: => T): Try[T] = {
Try(fn) match {
case x: Success[T] => x
case _ if retries > 1 => withRetry(retries - 1)(fn)
case f => f
}
}
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