Created
October 12, 2013 20:57
-
-
Save davidallsopp/6954845 to your computer and use it in GitHub Desktop.
Creating convenient syntax for retrying an unreliable operation, using Try, currying, call-by-name (and @tailrec, if you really need lots of retries!)
This is a Scala Eclipse worksheet, so won't run standalone without a minor tweak.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.annotation.tailrec | |
import scala.util.Random | |
import scala.util.{ Try, Success, Failure } | |
object retry { | |
{ // extra block is a workaround for Scala worksheet bug with @tailrec | |
@tailrec | |
def withRetry[T](attempts: Int)(f: => T): T = { | |
println("Attempts remaining: " + attempts) | |
Try(f) match { | |
case Success(t) => t | |
case Failure(_) if attempts > 1 => withRetry(attempts - 1)(f) | |
case Failure(e) => throw e | |
} | |
} | |
def unreliable(x: Int) = { | |
println("Unreliable") | |
val r = new Random() | |
if (r.nextInt(x) == 1) 1 else throw new Exception("Oops!") | |
} | |
// --------------------------------------------- | |
withRetry(3) { | |
unreliable(3) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment