I am writing a retry
function with async
and await
def awaitRetry[T](times: Int)(block: => Future[T]): Future[T] = async {
var i = 0
var result: Try[T] = Failure(new RuntimeException("failure"))
while (result.isFailure && i < times) {
result = await { Try(block) } // can't compile
i += 1
}
result.get
}
The Scala compiler reports an error. Since Try
doesn't have apply methods takes Future[T]
. So I solved it using implicit classes
implicit class TryCompanionOps(val t: Try.type) extends AnyVal {
// can't use `apply`!
def convertTriedFuture[T](f: => Future[T]): Future[Try[T]] =
f.map(value => Try(value))
}
// now we can convert Future[T] into Future[Try[T]] e.g,
await { Try.convertTriedFuture(block) }
My question is,
Why can't I use the name apply
instead of convertTriedFuture
? It seems that the scala compiler doesn't allow overload only about apply
methods in implicit classes.
Thanks.