Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a retry function?

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 ?

like image 472
Michael Avatar asked Jan 19 '26 03:01

Michael


1 Answers

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
  }
}
like image 199
Yuval Itzchakov Avatar answered Jan 21 '26 20:01

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!