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

前端 未结 14 1735
甜味超标
甜味超标 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:56

    This solution is not optimized by compiler to tail recursion for some reason (who knows why?), but in case of rare retries would be an option:

    def retry[T](n: Int)(f: => T): T = {
      Try { f } recover {
        case _ if n > 1 => retry(n - 1)(f)
      } get
    }
    

    Usage:

    val words: String = retry(3) {
      whatDoesTheFoxSay()
    }
    

    End of the answer. Stop reading here


    Version with result as a Try:

    def reTry[T](n: Int)(f: => T): Try[T] = {
      Try { f } recoverWith {
        case _ if n > 1 => reTry(n - 1)(f)
      }
    }
    

    Usage:

    // previous usage section will be identical to:
    val words: String = reTry(3) {
      whatDoesTheFoxSay()
    } get
    
    // Try as a result:
    val words: Try[String] = reTry(3) {
      whatDoesTheFoxSay()
    }
    

    Version with a function returning Try

    def retry[T](n: Int)(f: => Try[T]): Try[T] = {
      f recoverWith {
        case _ if n > 1 => reTry(n - 1)(f)
      }
    }
    

    Usage:

    // the first usage section will be identical to:
    val words: String = retry(3) {
      Try(whatDoesTheFoxSay())
    } get
    
    // if your function returns Try:
    def tryAskingFox(): Try = Failure(new IllegalStateException)
    
    val words: Try[String] = retry(3) {
        tryAskingFox()
    }
    

提交回复
热议问题