Michael
Michael

Reputation: 42100

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 ?

Upvotes: 3

Views: 1382

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149558

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
  }
}

Upvotes: 5

Related Questions