What's the Scala way to implement a retry-able call like this one?

前端 未结 14 1702
甜味超标
甜味超标 2020-11-29 16:08

Still the newbie in Scala and I\'m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destin         


        
14条回答
  •  -上瘾入骨i
    2020-11-29 16:53

    I like the accepted solution, but suggest checking the exception is NonFatal:

    // Returning T, throwing the exception on failure
    @annotation.tailrec
    def retry[T](n: Int)(fn: => T): T = {
      Try { fn } match {
        case Success(x) => x
        case _ if n > 1 && NonFatal(e) => retry(n - 1)(fn)
        case Failure(e) => throw e
      }
    }
    

    You don't want to retry a control flow exception, and usually not for thread interrupts...

提交回复
热议问题