Skip to content

Instantly share code, notes, and snippets.

@ToastShaman
Last active October 18, 2022 21:12
Show Gist options
  • Save ToastShaman/0dc59463a08b4b71c6a8182e1af75c67 to your computer and use it in GitHub Desktop.
Save ToastShaman/0dc59463a08b4b71c6a8182e1af75c67 to your computer and use it in GitHub Desktop.
A simple retry mechanism in Kotlin
fun <R> retry(
maxAttempts: Int,
action: () -> R
): R {
require(maxAttempts > 0) { "maxAttempts must be greater than 0" }
return runCatching(action).getOrElse {
val leftAttempts = maxAttempts.dec()
if (leftAttempts == 0) throw it
retry(leftAttempts, action)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment