如何编写重试功能? [英] How to write a retry function?

查看:84
本文介绍了如何编写重试功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数 foo:Int =>试试[Int] ,我需要重试。也就是说,我需要对其进行调用,直到它最多返回 k 成功

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.

我正在像这样编写函数 retry

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 ?

推荐答案

这是我使用的那个,对于返回 T :

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

这篇关于如何编写重试功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆